Abdussami Tayyab
Abdussami Tayyab

Reputation: 149

Populate a dropdown on selecting an option from another dropdown Laravel

Hope you're having a nice day and i'm much clear to describe my problem :)

I have a table of categories and a table of sub-categories. In my view, I want to let the user select a sub-category belonging to a category, for adding a product (Every product belongs to a sub-category). For that purpose, I want to show the user sub-categories when he selects a category. Like when he selects Clothes from Categories, I want to show Sub-categories like tops, shorts etc.

How do I do that? Just an idea would work.

Thanks.

Upvotes: 1

Views: 5925

Answers (2)

Dazz
Dazz

Reputation: 629

Try this

call getJSON in the first dropdown onChange and pass the selected value to url and load the results in the second dropdown. Hope this helps you

$(document).ready(function () {
    $("#firstdropdown").change(function () {
        var firstdropselectedvalue = $("#firstdropdown").val();
        var url = "test.php?selected=" + firstdropselectedvalue;
        $.getJSON(url, function (data) {
            $.each(data, function (index, text) {
                $("#seconddropdown").append($("<option></option>").val(index).html(text));
            });
        });
    });
});

Upvotes: 4

Abdussami Tayyab
Abdussami Tayyab

Reputation: 149

For those who are having a problem:

This is my function in my $(document.ready(function(){})); in my view

        $('#firstDropDown').change(function(){
        $.getJSON("{{ url('products/fetch-sub-category')}}", 
        { option: $(this).val() }, 
        function(data) {
            var model = $('#secondDropDown');
            model.empty();
            $.each(data, function(index, element) {
                model.append("<option value='"+element.catName+"'>" + element.catName + "</option>");
            });
        });
    });

And this is what i'm returning from my controller

    $input = Input::get('option');
    $cat = Category::where('catName', '=', $input)->get();
    return Response::json($cat, 200);

Upvotes: 6

Related Questions