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> <div class="code" style="position:relative; padding:0px; margin:0px;"><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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"1": ["Smartphone", "Charger"],
"2": ["Basketball", "Volleyball"]</pre><div class="contentsignin">Copy after login</div></div>
<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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const newOption = document.createElement("option");
newOption.value = option;
newOption.textContent = option;
itemsDropdown.appendChild(newOption);</pre><div class="contentsignin">Copy after login</div></div>
<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!