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:
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 ''
}).join('');
$locations.html(html)
});
});
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3