Populate one dropdown based on selection in another

0 votes
62 views
asked Jan 9, 2013 in java script by sahana (2,250 points)
i want to change the content of one dropdown based on the another dropdown selected item.

1 Answer

0 votes
answered Jan 9, 2013 by anonymous
edited Jan 9, 2013 by admin

 

 
try this one too
 
<select id='categoty' name='A'>
    
</select>
<select id='sub' name='B'>
</select>
 
        (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 = [['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
                A.appendChild(op);     
}
 
        //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
                B.appendChild(op);     
}
        };
        //fire this to update B on load
        A.onchange();
 
    })();

 

...