Home > Enterprise >  I try to make cascade dropdown with html and js
I try to make cascade dropdown with html and js

Time:10-31

I want to make cascade dropdowns, one for the city and one for neighbourhood this is my JS

var cityObject = {
    "City1": ["Neighborhood 1", "Neighborhood 2", "Neighborhood  3", "Neighborhood 4", "Neighborhood 5"],
    "City2": ["Neighborhood 1", "Neighborhood 2"],
    "City3": ["Neighborhood 1", "Neighborhood 2", "Neighborhood 3"],
    "City4": ["Neighborhood 1"]
}
window.onload = function() {
    var City = document.getElementById("City");
    var Neighborhood = document.getElementById("Neighborhood");
    for (var x in cityObject) {
        City.options[City.options.length] = new Option(x, x);
    }
    City.onchange = function() {
        Neighborhood.length = 1;
        var z = cityObject[City.value][this.value];
        for (var i = 0; i < z.length; i  ) {
            Neighborhood.options[Neighborhood.options.length] = new Option(z[i], z[i]);
        }
    }
}

and this is my HTML:

<select id="City" name="City"></select>
<select id="Neighborhood" name="Neighborhood">
   <option value="" selected="selected">Select city first</option>
</select>

I want first to select a city from the first select and second select load the Neighborhoods for the selected city

CodePudding user response:

You can use bellow code and also can run the snippet.

var cityObject = {
    "City1": ["Neighborhood 1", "Neighborhood 2", "Neighborhood  3", "Neighborhood 4", "Neighborhood 5"],
    "City2": ["Neighborhood 1", "Neighborhood 2"],
    "City3": ["Neighborhood 1", "Neighborhood 2", "Neighborhood 3"],
    "City4": ["Neighborhood 1"]
}

window.onload = function() {

    var City = document.getElementById("City");
    var Neighborhood = document.getElementById("Neighborhood");


    City.options[0] = new Option("Select a City", "");
    for (var x in cityObject) {
        City.options[City.options.length] = new Option(x, x);
    }
    
    
    City.onchange = function() {
    
        var nlist = ''; //declare neighborhood variable
        if(City.value != ''){ //if city value is not empty //city is selected
            var z = cityObject[City.value]; //get neighborhoods for the selected city
            
            nlist = '<option value="">Select a Neighborhood</option>';
            z.forEach(function(val){ //loop through neighborhoods
                nlist  = '<option value="' val '">' val '</option>';
            })
        }else{ // if city is not selected
            nlist = '<option value="">Select city first</option>';
        }
        
        Neighborhood.innerHTML = nlist; //print values in the neighborhood
        
    }
}
<html>
<head>
<title>asa</title>
</head>
<body>
    <select id="City" name="City"></select>
    <select id="Neighborhood" name="Neighborhood">
       <option value="">Select city first</option>
    </select>
</body>
</html>

  • Related