I have a ruby on rails application.I have 2 drop down boxes.I have to populate the second drop down box based on the selection from the first one.
The html code is
Basically you should add an event handler that will be triggered when the first drop-down is being changed that populates the second one based on the first one's selected option :
$('select#first').change(function(e){
var newOptions = getNewOptions($(this).val());
$('select#second').html(''); // clear the existing options
$.each(newOptions,function(i,o){
$('<option>' + o + '</option>').appendTo('select#second');
});
});
function getNewOptions(val){
if (val == 1)
return ['a','b','c'];
if(val == 2)
return [1,2,3,4];
return ['a1','a2','a3'];
}
And of course, your html markup is something like :
<select id="first">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="second">
</select>
Here's a working demo :
If you want to query the server for the new option list, in the change event handler, you should do an ajax request to the script that evaluates the current value of the first select-box and returns a list of options for the second one. In this ajax request callback you update the actual html based on the response :
$('select#first').change(function(e){
$.getJson('script_name',{value : $(this).val()},function(result){
$('select#second').html(''); // clear the existing options
$.each(result,function(i,o){
$("<option>" + o + "</option>").appendTo("select#second");
});
});
});