[英]Populate one dropdown list based on the selection of other dropdown list
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. 如果我选择一个名为car的类别,那么项目下拉列表应该包含Honda,Volvo,Nissan。
If I select one of the categories named phone, then item drop down list should have this iPhone, Samsung, Nokia. 如果我选择一个名为phone的类别,那么项目下拉列表应该有这个iPhone,三星,诺基亚。
How can I do this? 我怎样才能做到这一点? I know that I can't do it with plain HTML.
我知道我不能用纯HTML做到这一点。
WORKING DEMO http://jsfiddle.net/kasperfish/r7MN9/3/ (with jquery) 工作演示http://jsfiddle.net/kasperfish/r7MN9/3/ (与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.
更新 :使用eval()可以添加任意数量的数组。 JSFIDDLE DEMO
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.
这是最常见的2个。
This is the basic process: 这是基本过程:
AJAX (the most seamless experience with fewest page loads): AJAX(最少页面加载的无缝体验):
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. 如果您不想使用AJAX,您可以非常轻松地将表单POST到服务器端处理程序,从类别下拉列表中获取值,找到项目下拉列表的值,然后呈现HTML响应您为类别下拉列表设置了一个值并将其禁用(因此如果用户想要更改类别,则必须使用后退按钮)并填充项目下拉列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.