首頁 > web前端 > js教程 > 主體

如何根據使用者選擇填滿下拉式選單?

DDD
發布: 2024-10-18 13:12:03
原創
1079 人瀏覽過

How to Populately Dropdowns Based on User Selection?

Populating Dropdowns Based on Selection

When developing forms with multiple dropdowns, it can be beneficial to populate the options in one dropdown based on the selection made in another. This allows for a more user-friendly experience by narrowing down the choices and making data input more efficient.

One approach to achieving this functionality involves using JavaScript to dynamically update the content of the dependent dropdown. Here's an example that demonstrates how to populate one dropdown (B) based on the selection in another (A):

<code class="javascript">function configureDropDownLists(ddl1, ddl2) {
  var colours = ['Black', 'White', 'Blue'];
  var shapes = ['Square', 'Circle', 'Triangle'];
  var names = ['John', 'David', 'Sarah'];

  switch (ddl1.value) {
    case 'Colours':
      ddl2.options.length = 0;
      for (i = 0; i < colours.length; i++) {
        createOption(ddl2, colours[i], colours[i]);
      }
      break;
    case 'Shapes':
      ddl2.options.length = 0;
      for (i = 0; i < shapes.length; i++) {
        createOption(ddl2, shapes[i], shapes[i]);
      }
      break;
    case 'Names':
      ddl2.options.length = 0;
      for (i = 0; i < names.length; i++) {
        createOption(ddl2, names[i], names[i]);
      }
      break;
    default:
      ddl2.options.length = 0;
      break;
  }
}

function createOption(ddl, text, value) {
  var opt = document.createElement('option');
  opt.value = value;
  opt.text = text;
  ddl.options.add(opt);
}
登入後複製

This JavaScript function takes two parameters, ddl1 and ddl2, which represent the two dropdowns. It first initializes arrays with the options that will be displayed in each dropdown.

Next, a switch statement is used to handle the selection made in ddl1. Depending on the value of ddl1, it clears the options in ddl2 and populates it with the appropriate options. The createOption function is used to create and add each option to ddl2.

In the HTML, two dropdowns should be defined:

<code class="html"><select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
  <option value=""></option>
  <option value="Colours">Colours</option>
  <option value="Shapes">Shapes</option>
  <option value="Names">Names</option>
</select>

<select id="ddl2">
</select></code>
登入後複製

When the user selects an option in ddl1, the onchange event triggers the configureDropDownLists function, which updates the options in ddl2 accordingly. This approach provides a convenient way to populate one dropdown based on the selection in another, enhancing the usability of forms.

以上是如何根據使用者選擇填滿下拉式選單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板