How to Create a Cascading Dropdown Menu with Auto-Populating Second Menu?

Mary-Kate Olsen
Release: 2024-10-21 06:50:30
Original
282 people have browsed it

How to Create a Cascading Dropdown Menu with Auto-Populating Second Menu?

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

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

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!