views:

73

answers:

4

Hi

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="">

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?

A: 

change event is what you are after.

galambalazs
+2  A: 

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
Felix Kling
thanks! that works :D
Alex
A: 

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

Mark
A: 

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.

MisterZimbu