afujita afujita - 3 months ago 23
PHP Question

default select on ajax conditional dropdown select

Need help for setting up a default select option form my conditional dropdown select.

Here is my first dropdown select

<select name="category" id="category">
<option value="" disabled selected>Select category</option>
@foreach($categories as $cats)
<option value="{{$cats->id}}">{{$cats->name}}</option>
@endforeach
</select>


My dependent dropdown is like this

<select name="product" id="product">
<option value=""></option>
</select>


JS

<script>
$('#category').on('change',function(e){
console.log(e);

var cat_id = e.target.value;
$.get('/products?cat_id=' + cat_id, function(data){
$('#product').empty();

$.each(data, function(index, subcatObj){
$('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
});
});
</script>


For a simple dropdown select, like the categories one, simply used the and it worked fine, but how can I have this default select for the products drowdown select?

Appreciate any help.

Answer

You can append something like this

 $('#product').empty();
 $('#product').append('<option value="" disabled selected>Select Product</option>');
            });
$.each(data, function(index, subcatObj){
            $('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
            });

i have seen you have used $('#product').empty(); and hence your included <option value=""></option> is getting removed altogether which you put in your html.

You can use .html() instead of .append() so you do not need to $('#product').empty(); as .html() will overwrite your dom.

And then you can only need to put this in your html

<select name="product" id="product">

</select>

And your javascript will be something like this

<script>
    $('#category').on('change',function(e){
        console.log(e);

            var cat_id = e.target.value;
            var response = '';
            $.get('/products?cat_id=' + cat_id, function(data){
            response = '<option value="" disabled selected>Select Product</option>';

                  $.each(data, function(index, subcatObj){
                      response .= '<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>';
                  });

            $('#product').html(response);
            });
    });
</script>

you can find difference between .html() and .append() here What is the difference between .empty().append() and .html()?

Comments