开发者

jquery replicate values in to other area

IS there an easy way to replicate values in to other areas

i.e. if i have 2 or 3 select menus or other form fields.

say

<select id=first>
<option>1</option>
<option>2</option>
</select>

<select id=second>
<option>3</option>
<option>4</option>
</select>

<div id=firstvalue></div>
<div id=secondvalue></div>

If i want the divs html to aut开发者_Go百科omatically show the values of the select box, Would I have to do a piece of code for change on either component ?

Thanks

Lee


You want one code to work on both? Try this (example on jsFiddle)

$("select").change(function() // retrieve all `select` elements
   {
       // gets the corresponding `div`
       $("div").eq($(this).index())
           .html($(this).val()); // sets the html value of the `div` to
                                 // the selected value on the `select` element
   });

From jQuery docs:

  • Selectors
  • .change()
  • .eq()
  • .index()
  • .val()


If you want the divs to automatically show the selected value of any selectbox you can use the following jQuery:

$('#first').change(function(){ 
/* target the first selectbox with id #first and bind a change event to it */

    $('#firstvalue').html($(this).val()); 
    /* set the html of the div with id #firstvalue to the selected option*/

});

/* the same for the second selectbox */
$('#second').change(function(){

    $('#secondvalue').html($(this).val());

});

I would recommend changing your HTML though, so the selectboxes that are being handled have the same class and store their target within a data attribute. Like so:

HTML

<select class="show_val" data-target="#value_1">
    <option>1</option>
    <option>2</option>
</select>

<div id="value_1"></div>

jQuery

$('.show_val').change(function(){

    $($(this).data('target')).html($(this).val());

}

This way you can use the same jQuery event for all selectboxes.


You'd use the change event on the select box via the change or bind functions, and in the event handler you'd call the html or text function to set the text on the relevant div, getting the value of the selected option via val (your option elements don't have value attributes, so val will grab their text instead). In both cases, you look up the elements via the $ (or jQuery) function passing in a CSS selector (e.g., $("#first")) for the first select box.


You could do something like this so you wouldn't have to write code for each select/div:

$('select').change(function() {
    $('div[id^="' + this.id + '"]').text($(this).val());
});

JSFiddle Example


You could also check out knockout.js and implement the MVVM (Model-View-View-Model) pattern, if you're using a JavaScript backing object that is bound to the view/page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜