0

I'm Using Dependent select box(country & states)And it works well for me But when the data is not returned, the option is removed

<option>--States---</option>

I do not want to be removed I want when the data is not returned show the message to be displayed on

< option>--States---</ option>

(show default < option>)

how can I do that?

script:

<script>
$(document).ready(function() {

    $('select[name="country"]').on('change', function(){
        var countryId = $(this).val();
        if(countryId) {
            $.ajax({
                url: "{{route('home.state','')}}/" + countryId,
                type:"GET",
                dataType:"json",
                beforeSend: function(){
                    $('#loader').css("visibility", "visible");
                },
                success:function(data) {
                    $('select[name="state"]').empty();
                    $.each(data, function(key, value){
                        $('select[name="state"]').append('<option value="'+ key +'">' + 
           value + '</option>');
                    });
                },
                complete: function(){
                    $('#loader').css("visibility", "hidden");
                }
            });
        } else {

                    $('select[name="state"]').empty();
        }

    });

});
</script>
Nima
  • 81
  • 6

1 Answers1

1

You need to check if the returned object is empty .. Try the next code

<script>
$(document).ready(function() {
  $('select[name="country"]').on('change', function(){
      var countryId = $(this).val();
      if(countryId) {
         $.ajax({
            url: "{{route('home.state','')}}/" + countryId,
            type:"GET",
            dataType:"json",
            beforeSend: function(){
                $('#loader').css("visibility", "visible");
            },
            success:function(data) {
                $('select[name="state"]').empty();
                // check if object is empty //////////////////////////////////////
                if (Object.keys(data).length === 0 && data.constructor === Object) {
                  console.log('Empty Data Do anything Here');
                  $('select[name="state"]').append('<option value="" selected>----States----</option>');
                }else{ //////////////////////////////////////////////////////////
                  $.each(data, function(key, value){
                      $('select[name="state"]').append('<option value="'+ key +'">' + value + '</option>');
                  });
                }
            },
            complete: function(){
                $('#loader').css("visibility", "hidden");
            }
        });
      } else {
        $('select[name="state"]').empty();
      }
  });
});
</script>

You can take a look at How do I test for an empty JavaScript object?

Mohamed-Yousef
  • 22,772
  • 3
  • 17
  • 27