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

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?

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

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>

您可以为第一个 select 框创建一个 change listener 并填充 html第二个 select 框。

参见下面的演示:

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>

这将动态填充两个 selects:

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>