Jessica Mather Jessica Mather - 2 years ago 79
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:

<select name="colourone" id="firstcolour">
<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>

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:

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

Answer Source

You can use,

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

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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download