JSFiddle - React, Tailwind, and code Playground

by chrisallenmoore

HTML

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

CSS

select {
    text-transform: capitalize;
}

JavaScript

(function(){

    //setup an object fully of arrays
    //alternativly it could be something like
    //{"yes":[{value:sweet, text:Sweet}.....]}
    //so you could set the label of the option tag something different than the name
    var bOptions = {"all provinces":["all districts"],"bangkok":["all districts", "district 1","district 2","district 3"], "chiang mai":["all districts", "district 1","district 2"]};

    var A = document.getElementById('A');
    var B = document.getElementById('B');

    //on change is a good event for this because you are guarenteed the value is different
    A.onchange = function(){
        //clear out B
        B.length = 0;
        //get the selected value from A
        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
        for ( var i in bOptions[_val]){
            //create option tag
            var op = document.createElement('option');
            //set its value
            if(bOptions[_val][i] === "all districts") {
            	op.value = "";
            } else {
                op.value = bOptions[_val][i];            
            }
            //set the display label
            op.text = bOptions[_val][i];
            //append it to B
            B.appendChild(op);
        }
    };
    //fire this to update B on load
    A.onchange();

})();