Home >Backend Development >PHP Tutorial >How to Create Cascading Dropdowns Without a Database?
Problem:
In a form, you need two dropdowns, where the options of the second dropdown depend on the selection in the first dropdown, all without using a database.
Solution:
Despite the database method, here's how to achieve this without using one:
HTML Markup:
<code class="html"><select id="primary-dropdown"> <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="secondary-dropdown"> <option value="0" selected>None</option> </select></code>
JavaScript/jQuery:
<code class="javascript">$(document).ready(function() { var options = { 1: ["Smartphone", "Charger"], 2: ["Basketball", "Volleyball"], 3: ["Apple", "Orange"], 4: ["Dog", "Cat"] }; $("#primary-dropdown").on("change", function() { var selected = $(this).val(); $("#secondary-dropdown").empty(); $.each(options[selected], function(i, option) { $("#secondary-dropdown").append("<option value='" + (i + 1) + "'>" + option + "</option>"); }); }); });</code>
Explanation:
This solution allows you to create cascading dropdowns without relying on a database.
The above is the detailed content of How to Create Cascading Dropdowns Without a Database?. For more information, please follow other related articles on the PHP Chinese website!