I want to make an HTML form with 2 select boxes. The selected option in the first select box should drive the options in the second select box. I would like to solve this
Check out this example on Dynamic Drive, or you can search google for "chained select" for other examples.
Edit: And here is a very nice Remy Sharp tutorial: Auto-populating Select Boxes using jQuery & AJAX
Well, because I have OCD, I threw together a demo for you.
It defines a variable could also loaded as json if required.
HTML
<select id="cat"></select> <select id="items" disabled></select>
Script
$(document).ready(function(){
var menulist = { "categories" : [{
"category" : "Sandwiches",
"items" : [
{"name": "Turkey"},
{"name": "Ham"},
{"name": "Bacon"}
]
},{
"category" : "Sides",
"items" : [
{"name": "Mac 'n Cheese"},
{"name": "Mashed Potatoes"}
]
},{
"category" : "Drinks",
"items" : [
{"name": "Coca Cola"},
{"name": "Sprite"},
{"name": "Sweetwater 420"}
]
}]
};
var i,c = '<option>Select a category</option>', opt = $('<option/>');
var menu = menulist.categories;
for (i=0; i < menu.length; i++){
c += '<option>' + menu[i].category + '</options>';
}
$('#cat')
.html(c)
.change(function(){
var indx = this.selectedIndex - 1;
if (indx < 0) {
$('#items').empty().attr('disabled','disabled');
return;
}
var item = '<option>Select an item</option>';
for (i=0; i < menu[indx].items.length; i++){
item += '<option>' + menu[indx].items[i].name + '</options>';
}
$('#items').html(item).removeAttr('disabled');
});
});
You could do plain javascript. If this is all you need javascript for, then jQuery is probably too much.
create a function in the that populates the second combo box. In the first combo box, you call that function with onChange=theFunctionYouCreated()
hope that's enough to get you started.