根据另一个下拉列表填充一个下拉列表 [英] Populate one dropdown list based on another dropdown list
本文介绍了根据另一个下拉列表填充一个下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个下拉菜单,如下所示:
I have two dropdown menus as follows:
<form id="dynamicForm">
<select id="A">
</select>
<select id="B">
</select>
</form>
我有一个字典对象,其中的键是A
的选项,值B
是与A
中的每个元素相对应的数组,如下所示:
And I have a dictionary object where the keys are the options for A
and the values, B
are arrays corresponding to each element in A
, as follows:
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
}
如何根据用户在菜单A中选择的内容动态填充菜单B?
How can I dynamically populate the menu B based on what the user selects in menu A?
推荐答案
绑定更改事件处理程序并根据所选值填充第二个select标签.
Bind a change event handler and populate second select tag based on selected value.
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
}
// bind change event handler
$('#A').change(function() {
// get the second dropdown
$('#B').html(
// get array by the selected value
diction[this.value]
// iterate and generate options
.map(function(v) {
// generate options with the array element
return $('<option/>', {
value: v,
text: v
})
})
)
// trigger change event to generate second select tag initially
}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="dynamicForm">
<select id="A">
<option value="A1">A1</option>
<option value="A2">A2</option>
</select>
<select id="B">
</select>
</form>
这篇关于根据另一个下拉列表填充一个下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文