Country State City Drop Down List Using JavaScript In HTML

Country State City Drop Down List Using JavaScript In HTML
Code Snippet:JavaScript Dependent Dropdown List, Cascading Four Levels | Country, State, City, Zip Code Dropdown using JavaScript
Author: Mohammed Faysal.
Published: May 1, 2024
Last Updated: May 1, 2024
Downloads: 49
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript, HTML code helps you to create a Country State city drop-down list. It populates dropdowns based on user selection, providing location-specific options. Helpful for users to select specific locations easily.

You can use this code in web forms requiring location selection, like address forms or registration pages. Moreover,  this code provides a user-friendly interface for selecting countries, states, cities, and zip codes. This enhances user experience and ensures accurate data input.

How to Create Country State City Drop Down List Using JavaScript In HTML

1. Start by creating the basic HTML structure for your dropdowns. Place <select> elements within a <form> tag. Each selection should have a unique ID for JavaScript interaction.

<div class="container">
        <h2>Multi Level Dependent Drop Down</h2>

        <form action="#">
            <select name="" id="country">
                <option value="">-- Select Country --</option>
            </select>
            <select name="" id="state">
                <option value="">-- Select State --</option>
            </select>
            <select name="" id="city">
                <option value="">-- Select City --</option>
            </select>
            <select name="" id="zip">
                <option value="">-- Select Zip --</option>
            </select>
        </form>

    </div>

2. Apply basic styling to improve the visual presentation of the dropdowns. This makes them more user-friendly and consistent with your website’s design.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #EEEEEE;
}

.container{
    text-align: center;
}

.container h2{
    font-size: 2vw;
    font-family: 'Courier New', Courier, monospace;
    margin-bottom: 40px;
    letter-spacing: 1.2px;
}

form{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: 15px;
}

form select{
    width: 450px;
    padding: 15px;
    padding-left: 10px;
    background-color: #fff;
    border-radius: 10px;
    border: none;
    outline: none;
    font-size: 1.2rem;
    box-shadow: 0 5px 10px 0 rgb(0,0,0,0.25);
    cursor: pointer;
}

3. Finally, define a JavaScript object containing country, state, city, and zip code data. Then, use JavaScript to dynamically populate the dropdowns based on user selection.

var countrySateCityinfo = {
    Australia: {
        "Western Australia": {
            Broome: ["6725", "6318", "6701"],
            Coolgardie: ["6429", "6432"]
        },
        Tasmania: {
            Hobart: ["7000", "7520"],
            Launceston: ["7250", "7334"],
            Burnie: ["7320", "7315"]
        }
    },
    Germany: {
        Bavaria: {
            Munich: ["80331", "80333", "80335"],
            Numemberg: ["90402", "90403", "90404"]
        },
        Hessen: {
            Frankfurt: ["60306", "60309", "60310"],
            Surat: ["55246", "55247", "55248", "55249"]
        }
    },

    Canada: {
        Alberta: {
            Calgary: ["8033", "8333", "8035"],
            Edmonton: ["9040", "9403", "9040"]
        },
        Manitoba: {
            Brandon: ["6030", "6030"],
            Winnipeg: ["5524", "5547", "5248"]
        }
    }
    
}

window.onload = function(){
    const selectCountry = document.getElementById('country'),
        selectState = document.getElementById('state'),
        selectCity = document.getElementById('city'),
        selectZip = document.getElementById('zip'),
        selects = document.querySelectorAll('select')

        selectState.disabled = true
        selectCity.disabled = true
        selectZip.disabled = true

        selects.forEach(select => {
            if(select.disabled == true){
                select.style.cursor = "auto"
            }
            else{
                select.style.cursor = "pointer"
            }
        })

        for(let country in countrySateCityinfo){
            // console.log(country);
            selectCountry.options[selectCountry.options.length] = new Option(country, country)
        }


        // country change
        selectCountry.onchange = (e) =>{
            
            selectState.disabled = false
            selectCity.disabled = true
            selectZip.disabled = true

            selects.forEach(select => {
                if(select.disabled == true){
                    select.style.cursor = "auto"
                }
                else{
                    select.style.cursor = "pointer"
                }
            })

            selectState.length = 1
            selectCity.length = 1
            selectZip.length = 1

            for(let state in countrySateCityinfo[e.target.value]){
                // console.log(state);
                selectState.options[selectState.options.length] = new Option(state, state)
            }
        }

        // state change
        selectState.onchange = (e) =>{
            selectCity.disabled = false
            selectZip.disabled = true

            selects.forEach(select => {
                if(select.disabled == true){
                    select.style.cursor = "auto"
                }
                else{
                    select.style.cursor = "pointer"
                }
            })

            selectCity.length = 1
            selectZip.length = 1

            for(let city in countrySateCityinfo[selectCountry.value][e.target.value]){
                // console.log(city);
                selectCity.options[selectCity.options.length] = new Option(city, city)
            }
        }

        // change city
        selectCity.onchange = (e) =>{
            selectZip.disabled = false

            selects.forEach(select => {
                if(select.disabled == true){
                    select.style.cursor = "auto"
                }
                else{
                    select.style.cursor = "pointer"
                }
            })
            
            selectZip.length = 1

            let zips = countrySateCityinfo[selectCountry.value][selectState.value][e.target.value]
            
            for(let i=0; i<zips.length; i++){
                selectZip.options[selectZip.options.length] = new Option(zips[i], zips[i])
            }
        }
}

You’ve now created a multi-level dependent dropdown list using JavaScript in HTML. This allows users to easily select their location details, enhancing the usability of your web forms. Experiment with additional styling and customization to fit your website’s design.

Leave a Comment