I would like the choice of the first select element to determine the options of the next select element.
For example when someone chooses ‘Ug’ in the first select element, ONLY the options ‘A and B’ should be displayed in the next select element.
Likewise, when the option ‘Ke’ is chosen in the first select element, ONLY the options ‘C and D’ should be displayed in the next select element, ETC…
The current code doesn’t show any options in the second select once I click the first select element.
Could you please help me fix the issue with this code?
The code looks like below.
Thanks in advance!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control-selector" id="countryselect" name="countryselect" required>
<option class="select-option" value="" selected>- Choose Country</option>
<option class="select-option" value="Ug">Ug</option>
<option class="select-option" value="Ke">Ke</option>
<option class="select-option" value="Rw">Rw</option>
<option class="select-option" value="Tz">Tz</option>
<option class="select-option" value="SA">SA</option>
</select>
<select class="form-control-selector" id="cityselect" name="cityselect" required>
<option class="select-option" value="" selected>- Choose City </option>
<option class="select-option" value="A">A</option>
<option class="select-option" value="B">B</option>
<option class="select-option" value="C">C</option>
<option class="select-option" value="D">D</option>
<option class="select-option" value="E">E</option>
<option class="select-option" value="F">F</option>
<option class="select-option" value="G">G</option>
<option class="select-option" value="H">H</option>
<option class="select-option" value="I">I</option>
<option class="select-option" value="J">J</option>
</select>
<script>
$("#countryselect").change(function(){
var selectedOption = $("select option:selected").text();
$("#cityselect").empty();
for(var index=1;index<10;index++){
if(index>=parseInt(selectedOption)){
$("#cityselect").append($('<option></option>').html(index));
}
}
});
</script>
2
Answers
This code checks the selected option in the first select element (#countryselect) and populates the second select element (#cityselect) accordingly. You can extend the if conditions for each country and add their corresponding city options. If there are many countries, you might consider using a switch statement or a more advanced data structure to map countries to cities.
Instead of adding and removing options to the select element you can also enable/disable form fields. In this example each
cityselect
is in its own fieldset. All the fieldsets are initially disabled. When an option in the countryselect is selected the matching fieldset will be enabled.It is not an issue to have more form fields with the same name. If a form field or fieldset is disable the form field(s) are not included in the submit event.