Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a cascading Dropdown with JQuery

i have the following problem:

I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.

I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.

My original JS looks like this:

function populate(s1, s2) {
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    if (s1.value == "Germany") {
        var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
    } else if (s1.value == "Hungary") {
        var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
    } else if (s1.value == "Russia") {
        var optionArray = ["|", "st. petersburg|St. Petersburg"];
    } else if (s1.value == "South Africa") {
        var optionArray = ["|", "midrand|Midrand"];
    } else if (s1.value == "USA") {
        var optionArray = ["|", "downers grove|Downers Grove"];
    } else if (s1.value == "Mexico") {
        var optionArray = ["|", "puebla|Puebla"];
    } else if (s1.value == "China") {
        var optionArray = ["|", "beijing|Beijing"];
    } else if (s1.value == "Spain") {
        var optionArray = ["|", "barcelona|Barcelona"];
    }

    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);
    }
};

and here my Jquery:

http://jsfiddle.net/HvXSz/

i know it is very simple but i can't see the wood for the trees.

like image 823
user2609756 Avatar asked Aug 21 '13 08:08

user2609756


People also ask

How do I create a cascading dropdown in HTML?

Create three dropdown lists, inside an HTML form. The second and third dropdown list will display different options, depending on the value selected in the parent dropdown list.

What is a cascading drop down list?

A cascading drop-down list is a series of dependent DropDownList controls in which one DropDownList control depends on the parent or previous DropDownList controls. The items in the DropDownList control are populated based on an item that is selected by the user from another DropDownList control.


2 Answers

It should as simple as

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)
    });
});

Demo: Fiddle

like image 120
Arun P Johny Avatar answered Oct 14 '22 18:10

Arun P Johny


I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'. This is the first select:

<select class="select" id="province" onchange="filterCity();">
  <option value="1">RM</option>
  <option value="2">FI</option>
</select>

and this is the second, disabled until the first is selected:

<select class="select" id="city" disabled>
  <option data-province="RM" value="1">ROMA</option>
  <option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
  <option data-province="FI" value="3">FIRENZE</option>
  <option data-province="FI" value="4">PONTASSIEVE</option>
</select>

this one is not visible, and acts as a container for all the elements filtered out by the selection:

<span id="option-container" style="visibility: hidden; position:absolute;"></span>

Finally, the script that filters:

<script>

    function filterCity(){
      var province = $("#province").find('option:selected').text(); // stores province
      $("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
      var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
      toMove.appendTo("#option-container"); // moves city elements in #option-container
      $("#city").removeAttr("disabled"); // enables select
};
</script>
like image 34
marco bonfigli Avatar answered Oct 14 '22 18:10

marco bonfigli