Home >Backend Development >PHP Tutorial >How to Implement Auto-changing Options in Second Dropdown Menu Based on First Dropdown Selection?
When creating multiple dropdown menus where the options in the second menu depend on the selection made in the first menu, it is possible to achieve this without relying on a database.
The first dropdown menu will display a list of categories, while the second dropdown will display items associated with the selected category.
<select name="category"></p> <pre class="brush:php;toolbar:false"><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 name="items"><br></select><br>
To update the options in the second dropdown based on the selection in the first dropdown, we need an AJAX function that sends the selected category to a PHP script.
<script type="text/javascript"></p> <pre class="brush:php;toolbar:false">function ajaxfunction(parent) { $.ajax({ url: 'process.php?parent=' + parent; success: function(data) { $("#sub").html(data); } }); }
This function is attached to the onchange event of the first dropdown.
In the HTML, place another select element with an id of "sub" to display the dynamically generated options.
<select onchange="ajaxfunction(this.value)"></p> <pre class="brush:php;toolbar:false"><!-- Options would have been initially populated here -->
The process.php script will be responsible for generating the options for the second dropdown based on the selected category.
<?php</p><pre class="brush:php;toolbar:false">$parent = array( "First" => array("Smartphone", "Charger"), "Second" => array("Basketball", "Volleyball"), "Third" => array("Apple", "Orange"), "Fourth" => array("Dog", "Cat") ); foreach ($parent[$_GET["parent"]] as $id => $name) echo '<option value="', $id,'">', $name,'</option>'</p> <p>?><br>
In this case, we have used an array to define the category-item relationships. However, this can be easily adapted to retrieve the data from a database as well.
The above is the detailed content of How to Implement Auto-changing Options in Second Dropdown Menu Based on First Dropdown Selection?. For more information, please follow other related articles on the PHP Chinese website!