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