Jessica Mather Jessica Mather - 5 months ago 11
jQuery Question

How to populate an html select with another html select dynamically with Jquery

I want to take the selected value of this select:

<td>
<select name="colourone" id="firstcolour">
<option>--select--</option>
<option value="Red">Red</option>
<option value="Navy">Navy</option>
<option value="Royal Blue">Royal Blue</option>
<option value="Purple">Purple</option>
<option value="Gold">Gold</option>
<option value="Emerald Green">Emerald Green</option>
<option value="Maroon">Maroon</option>
<option value="White">White</option>
<option value="Black">Black</option>
</select>


And use jQuery to add the selected value from that select and add it to another select so that it dynamically populates.

This is what I tried:

$(document).add(function(){
$('#firstcolour').change(function(){
$('#colouroption').append($("<option>", {"value": listone_value, "text": listone_value})).insertAfter($('#blksize'));
});
});

Answer

You can use,

$('#firstcolour').change(function() {
  var option = $("<option>", {
    "value": $(this).val(),
    "text": $(this).find("option:selected").text()
  });
  $('#colouroption').append(option);
});

this will add the new option as the last one.

If you want to add the newly created option as the first one, then use prepend()

Comments