Home  >  Article  >  Backend Development  >  How to Update Dropdown Options Automatically Based on First Dropdown Selection Without a Database?

How to Update Dropdown Options Automatically Based on First Dropdown Selection Without a Database?

DDD
DDDOriginal
2024-10-21 06:48:29755browse

How to Update Dropdown Options Automatically Based on First Dropdown Selection Without a Database?

How to Automatically Update Options in a Second Dropdown Based on the Selection in a First Dropdown Without Using a Database

You have two dropdowns where the options are not retrieved from a database. The first dropdown allows the user to select a category. The options in the second dropdown depend on the selection in the first dropdown.

For example, if the user chooses the First option in the first dropdown, the second dropdown should display the options Smartphone and Charger. If the user changes their selection to the Second option, the second dropdown should now display the options Basketball and Volleyball.

Implementation without Using a Database

<select name="category" onchange="changeSecondDropdown(this)"></p>
<pre class="brush:php;toolbar:false"><option value="0">None</option>
<option value="1">First</option>
<option value="2">Second</option>

<script><br>function changeSecondDropdown(category) {<br> const options = {</p> <pre class="brush:php;toolbar:false">&quot;1&quot;: [&quot;Smartphone&quot;, &quot;Charger&quot;], &quot;2&quot;: [&quot;Basketball&quot;, &quot;Volleyball&quot;]</pre> <p>};</p> <p>// Clear the options in the second dropdown<br> const itemsDropdown = document.getElementById("items");<br> itemsDropdown.innerHTML = "";</p> <p>// Add the new options based on the selected category<br> const selectedOptions = options[category.value];<br> for (const option of selectedOptions) {</p> <pre class="brush:php;toolbar:false">const newOption = document.createElement(&quot;option&quot;); newOption.value = option; newOption.textContent = option; itemsDropdown.appendChild(newOption);</pre> <p>}<br>}<br></script>

This implementation uses a JavaScript object to store the options for each category. When the user changes the selection in the first dropdown, the changeSecondDropdown function is called, which updates the options in the second dropdown based on the selected category.

The above is the detailed content of How to Update Dropdown Options Automatically Based on First Dropdown Selection Without a Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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