Home > Backend Development > PHP Tutorial > How to Create Cascading Dropdowns Without a Database?

How to Create Cascading Dropdowns Without a Database?

Susan Sarandon
Release: 2024-10-21 06:47:02
Original
416 people have browsed it

How to Create Cascading Dropdowns Without a Database?

Selecting Cascading Dropdowns Without 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>
Copy after login

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>
Copy after login

Explanation:

  • We define an object called options to hold the associations between the primary dropdown values and their corresponding secondary dropdown options.
  • When the primary dropdown value changes, we empty the secondary dropdown and loop through the options object.
  • For the selected primary dropdown value, we append the corresponding options to the secondary dropdown.

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template