Changing the value of dynamically created dropdowns
I have a list of drop-down elements dynamically created in my server side code.
<select id="color1">
<option value="blue">blue</option>
<option value="red">red</option>
<option value="green">green</option>
</select>
<select id="color2">
<option value="white">white</option>
<option value="orange">orange</option>
<option value="green">green</option>
</select>
<select id="color3">
<option value="black">black</option>
<option value="pink">pink&开发者_高级运维lt;/option>
<option value="brown">brown</option>
</select>
<select id="color4">
<option value="yellow">yellow</option>
<option value="black">black</option>
<option value="green">green</option>
</select>
I would require to write code in jQuery to change the value of all the SELECT values on a button click based on the selection of one of the SELECT elements.
For Eg: If I select red in the first SELECT, all the SELECT element value should be changed to red. If the value is already present in the target SELECTs, we just need to select the value, otherwise we need to append it.
Is it possible to write it in jQuery?
$selected = $('#color1 option:selected');
val = $selected.attr('value');
$('select:not(#color1)').each(function(i) {
$opt = $('option[value='+val+']', $(this));
if(!$opt.length) {
$(this).append($selected).attr('selected', 'selected');
} else {
$opt.attr('selected', 'selected');
}
});
Have not tested, though. Hope it's a good base to build on. Don't forget to attach it to the select
event handler of the #color1
, or to a click
handler of a button of your choice.
精彩评论