Home > Web Front-end > JS Tutorial > body text

How to Populate Dropdown Contents Dynamically Using JavaScript?

Mary-Kate Olsen
Release: 2024-10-18 13:14:02
Original
928 people have browsed it

How to Populate Dropdown Contents Dynamically Using JavaScript?

Dynamic Dropdown Population via Javascript

In a scenario where you need to populate the contents of one dropdown (B) based on the selection made in another dropdown (A) using JavaScript, there's no need for complex AJAX queries. Instead, you can leverage the following code snippet to accomplish this:

<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);
}
Copy after login

To utilize this code, include it in your JavaScript file and register the configureDropDownLists function as the onChange event handler for your first dropdown (A):

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

<select id="ddl2">
</select></code>
Copy after login

This code demonstrates how to populate the second dropdown (ddl2) based on the selection in the first dropdown (ddl1), utilizing switch-case logic to dynamically determine the content of ddl2.

The above is the detailed content of How to Populate Dropdown Contents Dynamically Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template