javascript:动态下拉菜单值 [英] javascript: dynamic drop down menu values
问题描述
我想创建两个下拉表单,如果我在第一个菜单上选择一个项目,第二个菜单将显示相应的值。例如:如果我在第一个菜单上选择水果,那么第二个菜单将显示apple,banana等。它必须有值,所以我可以将它插入数据库。
i want to create two drop down form and if i select an item on the first menu the second menu will display corresponding value. for example: if i select "fruit" on the first menu, then the second menu will display "apple", "banana" and so on. it must have values on them so i can insert it into database.
html如下:
<select id="firstmenu" name="fruit">
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<br/>
<select id="secondmenu" name="vegetable">
<option value="carrot">carrot</option>
<option value="celery">celery</option>
</select>
javascript;我正在考虑使用类似的东西,但我不了解javascript
javascript; i was thinking using something like this but i lack understanding of javascript
<script>
var a=document.forms["myform"]["fruit"].value;
var b=document.forms["myform"]["vegetable"].value;
if (a=="fruit")
{
...
}
</script>
有人可以给我一个代码示例吗?非常感谢帮助。谢谢。
could someone give me a code example? help is much appreciated, thanks.
推荐答案
好吧,
如何关于使用jQuery?
how about using jQuery?
http://jsfiddle.net / W4m9S / 1 /
var items = [
{
name: '---',
value:'',
subitems: []
},
{
name:'Fruit',
value: 'fruit',
subitems: [
{name: 'Apple', value: 'apple'},
{name:'Banana', value:'banana'}
]
},
{
name: 'Vegetable',
value: 'vegetable',
subitems: [
{name: 'Carrot', value:'carrot'},
{name: 'Celery', value:'celery'}
]
}
];
$(function(){
var temp = {};
$.each(items, function(){
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo("#firstmenu");
temp[this.value] = this.subitems;
});
$("#firstmenu").change(function(){
var value = $(this).val();
var menu = $("#secondmenu");
menu.empty();
$.each(temp[value], function(){
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo(menu);
});
}).change();
});
这篇关于javascript:动态下拉菜单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!