I want to create two drop down lists, category and item.
If I select one of the categories named car, then item drop down list should have Honda, Volvo, Nissan.
If I select one of the categories named phone, then item drop down list should have this iPhone, Samsung, Nokia.
How can I do this? I know that I can't do it with plain HTML.
WORKING DEMO http://jsfiddle.net/kasperfish/r7MN9/3/ (with jquery)
cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');
populateSelect();
$(function() {
$('#cat').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#cat').val();
$('#item').html('');
if(cat=='car'){
cars.forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}
if(cat=='phone'){
phones.forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}
}
UPDATED: using eval() to be able to add as much arrays as you want. JSFIDDLE DEMO
cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');
names=new Array('Kasper','Elke','Fred','Bobby','Frits');
colors=new Array('blue','green','yellow');
populateSelect();
$(function() {
$('#cat').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#cat').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}
There are numerous ways that you can accomplish this depending on what your end goal is. Here are the 2 most common ones.
This is the basic process:
AJAX (the most seamless experience with fewest page loads):
If you don't want to use AJAX, you could very easily POST the form to a Server-side handler, get the value from the category drop-down, locate your values for the item drop-down and then render your HTML response in which you set a value for the category drop-down and disable it (so the user would have to use the back button if they would wanted to change the category) and populate the item drop-down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With