开发者

jQuery - hidden input value from select inputs

I have something like this:

<select class="bla">
  <option value="1">...</option>
  <option value="2">...</option>
</select>

<select class="bla">
  <option value="1">...</option>
  <option value="2">...</option>
</select>

<select class="bla">
  <option value="1">...</option>
  <option value="2">...</option>
</select>

<input class="alloptions" type="hidden" value="">
开发者_如何学Python

I want the hidden input field value to change every time a different option is selected in each of the select input fields above. This value would contain the selected options from all input fields separated with commas.

How can I do this?


Something like:

$('select.bla').change(function() {
    $value = $('select.bla').map(function(){return $(this).val()}).get().join(',');
    $('input.alloptions').val($value);
});

Explanation:

  • change() gets fired whenever the value of a select field changes
  • With map() we create an array of the values of the select fields and join them to a string separated by commas


change event is what you are after.


The .serialize() method can act on a jQuery object that has selected individual form elements, such as "input", "textarea", and "select" - meaning you could do the following:

$('.bla').change(function(){
   var opts = $('select').serialize();
   $('.alloptions').val(opts);
});

Each "select" would need a name value and would produce:

selec1=1&select2=2&select3=1


Do you really need to use Javascript for that? If you give all three select boxes the same "name" attribute, the values will be sent to the server as a comma-delimited list.

Just make sure that you do a trim of each element when you do a split, as some browsers will put spaces after the commas.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜