JSFiddle - React, Tailwind, and code Playground

by chrisallenmoore

HTML

<select id='P' name='P'>
    <option value=''  selected='selected'>All Provinces</option>
    <option value='bangkok'>Bangkok</option>
    <option value='chiang mai'>Chiang Mai</option>
</select>
<select id='D' name='D'>
</select>

CSS

select {
    text-transform: capitalize;
}

JavaScript

(function(){

    var pdOptions = [
        {
            "name": "all provinces",
            "districts": ["all districts"]
    },
        {
        "name": "bangkok",
        "districts": ["all districts","district 1","district 2","district 3", "district 4"]
    },
        {
        "name": "chiang mai",
        "districts": ["all districts","cm district 1","cm district 2","cm district 3"]
    }
    ];

    var P = document.getElementById('P');
    var D = document.getElementById('D');

    //on change is a good event for this because you are guarenteed the value is different
    P.onchange = function(){
        //clear out D
        D.length = 0;
        //get the selected value from P
        var _val = this.options[this.selectedIndex].value;
        
        // if all provinces, option value is '', so make _val = "all provinces" to make "All Districts" show.
       	if (_val === "") {
            _val = "all provinces";
        }
        
        //loop through bOption at the selected value    
        var i;
        for (var i in pdOptions){
            //create option tag
            
            //set its value
            if(pdOptions[i].name === _val) {
                var x;
                for (var x in pdOptions[i].districts){
                    var op = document.createElement('option');
                    if (pdOptions[i].districts[x] === "all districts") {
                        op.value = "";
                    } else {
                        op.value = pdOptions[i].districts[x];
                    }         
                    // set the text on Districts
                    op.text = pdOptions[i].districts[x];
                    // append it to Districts
                    D.appendChild(op);
            	}
            }
            
        }
    };
    //fire this to update Districts on change of Provinces
    P.onchange();

})();