[英]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.