0 votes
asked in java script by (2.3k points)
i want to change the content of one dropdown based on the another dropdown selected item.

1 Answer

0 votes
answered by
edited by


try this one too
<select id='categoty' name='A'>
<select id='sub' name='B'>
        //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 = [['ten', ['eleven','twelve']],['twenty', ['twentyone', 'twentytwo']]];
        var A = document.getElementById('categoty');
        var B = document.getElementById('sub');
      for(var i = 0; i < bOptions.length; i++) {
    var op = document.createElement('option');
                //set its value
                op.value = bOptions[i][0];
                //set the display label
                op.text = bOptions[i][0];
                //append it to 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.selectedIndex;
            var _option = bOptions[_val][1];           
            //loop through bOption at the selected value
            for(var i = 0; i < _option.length; i++) {
    var op = document.createElement('option');
                //set its value
                op.value = _option[i];
                //set the display label
                op.text = _option[i];
                //append it to B
        //fire this to update B on load