繁体   English   中英

根据另一个下拉列表填充一个下拉列表

[英]Populate one dropdown list based on another dropdown list

我有两个下拉菜单如下:

<form id="dynamicForm">
  <select id="A">

  </select>
  <select id="B">

  </select>
</form>

我有一个字典对象,其中键是A的选项,值是, B是与A每个元素对应的数组,如下所示:

var diction = {
    A1: ["B1", "B2", "B3"], 
    A2: ["B4", "B5", "B6"]
}

如何根据用户在菜单A中选择的内容动态填充菜单B?

绑定更改事件处理程序并根据所选值填充第二个选择标记。

 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> 

您可以为第一个选择框创建更改侦听器 ,并填充第二个选择框的html

见下面的演示:

 var diction = { A1: ["B1", "B2", "B3"], A2: ["B4", "B5", "B6"] } $('#A').on('change', function() { $('#B').html( diction[$(this).val()].reduce(function(p, c) { return p.concat('<option value="' + c + '">' + c + '</option>'); }, '') ); }).trigger('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> 

这将动态填充两个select

 var diction = { A1: ["B1", "B2", "B3"], A2: ["B4", "B5", "B6"] }; // the function that will populate the select function populateSelect(id, values) { // get the select element var $select = $(id); // empty it $select.empty(); // for each value in values ... values.forEach(function(value) { // create an option element var $option = $("<option value='" + value + "'>" + value + "</option>"); // and append it to the select $select.append($option); }); } // when the #A select changes ... $("#A").on("change", function() { // get the value of the selected element (the key) var key = $(this).val(); // populate #B accordingly populateSelect("#B", diction[key]); }); // Before anything, populate #A with the keys of diction and ... populateSelect("#A", Object.keys(diction)); // ... #B with whatever #A hold its key populateSelect("#B", diction[$("#A").val()]); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="dynamicForm"> <select id="A"> </select> <select id="B"> </select> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM