Home >Web Front-end >JS Tutorial >How to Dynamically Populate Cascading Dropdowns with jQuery?
Creating a form with two dropdowns (Country and City), you need to make them dynamic so that only the cities of the selected country are visible. You've converted your JavaScript to jQuery for better compatibility, but you're still facing some issues.
<code class="javascript">function populate(s1, s2) { var optionArray; switch (s1.value) { case "Germany": optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"]; break; // ... more cases default: optionArray = ["|"]; } for (var option in optionArray) { var pair = optionArray[option].split("|"); var newOption = document.createElement("option"); newOption.value = pair[0]; newOption.innerHTML = pair[1]; s2.options.add(newOption); } }</code>
The following jQuery code achieves the desired result:
<code class="javascript">jQuery(function($) { var locations = { 'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'], 'Spain': ['Barcelona'], 'Hungary': ['Pecs'], 'USA': ['Downers Grove'], 'Mexico': ['Puebla'], 'South Africa': ['Midrand'], 'China': ['Beijing'], 'Russia': ['St. Petersburg'], } var $locations = $('#location'); $('#country').change(function () { var country = $(this).val(), lcns = locations[country] || []; var html = $.map(lcns, function(lcn){ return `<option value="${lcn}">${lcn}</option>` }).join(''); $locations.html(html) }); });</code>
This code stores the country-city relationships in the locations object. When the country dropdown is changed, the change event handler gets the selected country and retrieves the corresponding cities from the locations object. It then constructs HTML options for the cities and replaces the contents of the location dropdown.
The above is the detailed content of How to Dynamically Populate Cascading Dropdowns with jQuery?. For more information, please follow other related articles on the PHP Chinese website!