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

Laracast13's avatar

laravel dependent dropdown check

Hi

Have dependent dropdown which return data.

ajax have three values and when all of them is set it gives result.

But I need add check, when a, b , c all this value is set send ajax request , now it send if one of them is set.

I need do this check, in jQuery on in controller.

In controller I try check with $a_id != null && $b_id != null && $c_id != null but this not works. In jQuery I use if(c_id) , but this always give true, also when nothing selected and by default it have Choose

<select id="a_id">
<option selected="selected" value="">Choose</option> 
<option value="list1">list1</option> 
<option value="list2">list2</option> 
<option value="list3">list3</option> 
</select>


<select id="b_id">
<option selected="selected" value="">Choose</option> 
<option value="list22">list2-1</option> 
<option value="list222">list2-2</option> 
<option value="list2222">list2-3</option> 
</select>


<select id="c_id">
<option selected="selected" value="">Choose</option> 
<option value="list33">list3-1</option> 
<option value="list333">list3-2</option> 
<option value="list333">list3-3</option> 
</select>
        $('#a, #b, #c').on('change', function(){ 
            var a_id = $("#a_id").val();
            var b_id = $("#b_id").val();
            var c_id = $("#c_id").val(); 
            if(c_id) {
                $.ajax({
                    url: "{{  url('/get/') }}/"+a_id+"/"+b_id+"/"+c_id,
                    type:"POST",
                    dataType:"json",
                    success:function(data) {
                      if(data){
                        $("#p").empty();  
                           ///
console.log(data); 
     
                      }else{ $("#p").empty();} 
                    },
                });
            } else {$("#p").empty();}
        });

Controller

    public function getData($a_id = null, $b_id = null, $c_id = null)
    {          
        $a = Aaa::findOrFail($a_id);
        $b = Bbb::findOrFail($b_id);
        $c = Ccc::findOrFail($c_id);  
        return response()->json(['a' => $a, 'b' => $b, 'c' => $c]);  
    }
0 likes
1 reply
MarianoMoreyra's avatar
Level 25

Hi @www888

It’s passes because empty string “” is not null in JavaScript. Try with the following:

             if(a_id != “” && b_id != “” && c_id != “”) {
                $.ajax({
                    url: "{{  url('/get/') }}/"+a_id+"/"+b_id+"/"+c_id,
                    type:"POST",
                    dataType:"json",
                    success:function(data) {
                      if(data){
                        $("#p").empty();  
                           ///
console.log(data); 
     
                      }else{ $("#p").empty();} 
                    },
                });
            } else {$("#p").empty();} 

Hope this works

1 like

Please or to participate in this conversation.