Home > Backend Development > PHP Tutorial > How to Auto-Update Options in a Second Drop Down Menu Based on Selections in the First Drop Down Menu?

How to Auto-Update Options in a Second Drop Down Menu Based on Selections in the First Drop Down Menu?

Patricia Arquette
Release: 2024-10-21 06:47:30
Original
769 people have browsed it

How to Auto-Update Options in a Second Drop Down Menu Based on Selections in the First Drop Down Menu?

First Drop Down Menu Auto-updates Options in Second Drop Down Menu

Problem Statement:

Develop two drop-down menus where the options in the second drop-down menu depend on the selection made in the first drop-down menu. This functionality is desired without utilizing a database.

Solution:

Initial HTML:

<code class="html"><select id="category">
  <option value="0">None</option>
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

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

JavaScript:

Define a function to handle the change event of the first drop-down menu and update the options in the second drop-down menu accordingly.

<code class="javascript">document.getElementById("category").addEventListener("change", function() {
  var category = this.value;

  var items = document.getElementById("items");
  items.innerHTML = "";

  switch (category) {
    case "1":
      items.innerHTML = '<option value="3">Smartphone</option><option value="8">Charger</option>';
      break;
    case "2":
      items.innerHTML = '<option value="1">Basketball</option><option value="4">Volleyball</option>';
      break;
    default:
      break;
  }
});</code>
Copy after login

Explanation:

In this example, the options for the second drop-down menu are hardcoded within the JavaScript function. When the user selects a category from the first drop-down menu, the change event triggers the JavaScript function. Based on the selected category, the function dynamically updates the options in the second drop-down menu.

The above is the detailed content of How to Auto-Update Options in a Second Drop Down Menu Based on Selections in the First Drop Down Menu?. 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