Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Nael.Saeed's avatar

Updating dropdown list B when choosing from dropdown list A

hello, I have a form with 2 dropdown lists A and B. I am using bootstrap and Laravel. I want to populate dropdown list B relatively to the option chosen in dropdown list A. What is the best way to do so ?

Thanks

0 likes
3 replies
FrancescoZaffaroni's avatar

Depends, is the content you want to populate them on the server? If it is and it's a lot you can send an ajax request when you select the first and on response populate the second.

cent040's avatar
 <div id="category"> </div>

JavaScript Code :

 $("#type_id").on("change", function () {
            var form_data = {
                 type_id: $("#type_id").val()
             };
             $.ajax({
                 type: 'POST',
                  url: 'ajax_categories.php',
                  data: form_data,
                 success: function (msg) {
                    $("#category").html(msg);
                    $("#cat_id").hide();

            }
        });
    });

PHP (ajax_categories.php) Return Html

  $categories = get_categories($type_id);
    $options = '<div>
    <select name="category_id" id="category_id" > ';
    foreach ($categories as $cat) {
        $options .= "<option value='" . $cat->id . "'>" . $cat->name . "</option> ";
    }
    $options .= "</select></div>";
Nael.Saeed's avatar

@FrancescoZaffaroni @cent040 Thanks for your reply. I need to know how to use that inside my Laravel application. There are alot of examples online about using ajax, but using it the right way inside my Laravel controllers and view.blade.php is what I need to learn

Please or to participate in this conversation.