hgarciap hgarciap - 4 months ago 10
jQuery Question

Populate a select with options selected from various selects - jquery

I´m not expert with javascript & jquery, and I just googled for many days but can´t find the answer.

How can I populate a select with options selected from other selects. For this example from the 1st select I choose Manchester, from 2nd I choose Bogota and the 3rd must be populated with Manchester and Bogota:

Select One <br>
<select id="city" name="city">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="2">Paris</option>
<option value="3">Madrid</option>
</select><br>

Select 2 <br>
<select id="city2" name="city2">
<option value="0"></option>
<option value="4">Bogota</option>
<option value="5">Buenos Aires</option>
<option value="6">Quito</option>
</select><br>

Select 3, populated whit the options of the previous 2 selects <br>
<select id="street" name="street">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="4">Bogota</option>
</select>


Many thanks for help me.

Answer

The following jQuery will refresh the street select list any time a change is made to a select with class refresh on it.

function refreshList() {
 
  $('#street option').remove(); //Clear the dropdown
  $('#street').append('<option value="0"></option>'); //Add the blank option
  
  $('.refresh').each(function() { //Loop through every instance of class 'refresh'
    
    var v = $(this).val(); //Selected Value
    var t = $(this).find('option[value="' + v + '"]').text(); //Selected Text
    
    if (v != 0) { //If value isn't blank, add option to Street
     $("#street").append('<option value="' + v + '">' + t + '</option>'); 
    }
  });
  
}

$(document).ready(function() { //When the page loads
  
   $('.refresh').change(function() { //Initialize a click-event listener for class 'refresh'
    
    refreshList(); //Run above function
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select One <br>
<select id="city" name="city" class="refresh">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="2">Paris</option>
<option value="3">Madrid</option>
</select><br>

Select 2 <br>
<select id="city2" name="city2" class="refresh">
<option value="0"></option>
<option value="4">Bogota</option>
<option value="5">Buenos Aires</option>
<option value="6">Quito</option>
</select><br>

Select 3, populated with the options of the previous 2 selects <br>
<select id="street" name="street">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="4">Bogota</option>
</select>

Comments