Populating a Cascading Dropdown with JQuery
Problem:
You aim to create a dynamic form with two dropdowns (Country and City) using JQuery, ensuring that only the cities corresponding to the selected country are displayed in the City dropdown.
Original JavaScript Code:
The original JavaScript function, while working, faces compatibility issues in Internet Explorer. It dynamically populates the City dropdown based on the selected country, relying on hardcoded arrays of city options.
JQuery Implementation:
To enhance compatibility and simplify the implementation, JQuery can be employed. Here's an efficient approach using JQuery:
<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>
Explanation:
Demo:
You can refer to the provided Fiddle link for a working demo.
This JQuery implementation is concise, cross-browser compatible, and facilitates the dynamic population of the cascading dropdown.
The above is the detailed content of How to Populate a Cascading Dropdown with Cities Based on Selected Country Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!