Cascading Dropdown Menu: Auto-Populating Second Menu Based on First Selection
In this scenario, we want to create two interconnected dropdown menus, where the options in the second menu change dynamically based on the selection made in the first menu.
Initial HTML Structure:
<code class="html"><select name="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 name="items"> <!-- Options will be populated dynamically --> </select></code>
Event Handling:
To achieve the desired functionality, we will use an event listener on the first dropdown to trigger an Ajax call when the selection changes.
<code class="javascript"><script type="text/javascript"> function changeItems(categoryId) { $.ajax({ url: 'process.php?category=' + categoryId, success: function(data) { $("#items").html(data); } }); } </script></code>
Handling the Ajax Request:
In the process.php file, we will construct the options for the second dropdown based on the selected category.
<code class="php">$categoryId = $_GET['category']; switch ($categoryId) { case 1: $options = array( 'Smartphone', 'Charger' ); break; case 2: $options = array( 'Basketball', 'Volleyball' ); break; // ... } foreach ($options as $option) { echo "<option value='$option'>$option</option>"; }</code>
Dynamically Updating the Second Dropdown:
The Ajax call populates the #items element with the new options generated in process.php.
<code class="javascript">$("#items").html(data);</code>
Custom Implementation without Database:
If you do not have a database, you can manually define the options for each category in an array and update the second dropdown through JavaScript.
<code class="javascript">// Define options for each category const categories = ['First', 'Second', 'Third', 'Fourth']; const optionArrays = [ ['Smartphone', 'Charger'], ['Basketball', 'Volleyball'], // ... ]; // Update second dropdown on category change $(document).on('change', 'select[name="category"]', function() { const selectedCategory = $(this).val(); const options = optionArrays[selectedCategory - 1]; // Subtract 1 to match array indices $('#items').empty(); for (let i = 0; i < options.length; i++) { $('#items').append(`<option value="${options[i]}">${options[i]}</option>`); } });</code>
The above is the detailed content of How to Create a Cascading Dropdown Menu with Auto-Populating Second Menu?. For more information, please follow other related articles on the PHP Chinese website!