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

时间:2017-01-28 04:11:15

标签: javascript jquery html arrays jquery-events

我有两个下拉菜单如下:

<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?

3 个答案:

答案 0 :(得分:3)

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

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>

答案 1 :(得分:3)

您可以为第一个选择框创建更改侦听器,并填充第二个选择框的 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>

答案 2 :(得分:1)

这将动态填充select s:

&#13;
&#13;
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()]);
&#13;
<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>
&#13;
&#13;
&#13;