Home  >  Article  >  Web Front-end  >  How to Populate a Cascading Dropdown with JQuery in IE?

How to Populate a Cascading Dropdown with JQuery in IE?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 16:52:02437browse

How to Populate a Cascading Dropdown with JQuery in IE?

Populating a Cascading Dropdown with JQuery

Problem:

In order to create a more interactive user experience, you want to populate a dropdown with options dynamically based on the selection made in a parent dropdown. You've attempted to do this using JavaScript, but you're facing compatibility issues in IE.

Solution:

To enhance compatibility and simplify the implementation, let's convert your JavaScript code to JQuery. Here's how you can achieve cascading dropdowns 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:

  • We define a locations object to store all the possible locations for each country.
  • When the country dropdown changes, the change() event handler is triggered.
  • We retrieve the selected country and the corresponding locations array from the locations object.
  • Using JQuery's $.map() function, we create a string of HTML options representing the locations.
  • Finally, we populate the #location dropdown with the generated HTML options.

Demo:

Try out a live demo on Fiddle: https://jsfiddle.net/HvXSz/.

The above is the detailed content of How to Populate a Cascading Dropdown with JQuery in IE?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn