"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Populate a Cascading Dropdown with Cities Based on Selected Country Using jQuery?

How to Populate a Cascading Dropdown with Cities Based on Selected Country Using jQuery?

Published on 2024-11-25
Browse:119

How to Populate a Cascading Dropdown with Cities Based on Selected Country Using jQuery?

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:

  • We define an object locations that maps countries to arrays of corresponding cities.
  • The change event handler for the Country dropdown triggers the dynamic population of the City dropdown.
  • The event handler gets the selected country and retrieves the corresponding city array from the locations object.
  • A loop creates HTML option elements for the cities and appends them to the City dropdown using $locations.html(html).

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.

Latest tutorial More>

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