简体   繁体   中英

Check if an array is empty

I've tried several things which are listed on the forum here, but I can't get this one to work.

So my question: How to check if an array is empty and if so hide an element?

Perhaps I'm doing something completly wrong?

My code:

 var listaSelection = {
                "category": [{ value: "1234", text: "Test" }]};

            $("select#list").change(function(){

              $("#cat3").html($("#list option:selected").text());

              var options = '';
              listsa = listaSelection[$(this).val()];

              $('select#listA').empty();

              options += '<option value="">Choose</option>';

              $.each(listsa, function() {
                options += '<option value="' + this.value + '">' + this.text + '</option>';
              });
              if(listsa.length > 0){   
                $('select#listA').append(options);
                $('.zoeken-select.listA').fadeIn(300);
              }else{
                //this array is empty
                return false;
              }

            }); 

The HTML

<div class="zoeken-select course">
              <div class="zoeken-value" id="cat2">Selecteer je sector/locatie</div>
              <div class="zoeken-handle"></div>
              <select id="course" class="gui-validate">
              </select>
            </div>
            <div class="zoeken-select list">
              <div class="zoeken-value" id="cat3"></div>
              <div class="zoeken-handle"></div>
              <select id="list" class="gui-validate">
              </select>
            </div>
            <div class="zoeken-select listA">
              <div class="zoeken-value" id="cat4"></div>
              <div class="zoeken-handle"></div>
              <select id="listA" class="gui-validate">
              </select>
            </div>

Use the isEmptyObject method

jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false

use

jQuery.isEmptyObject({});

see EmptyObject

for array

 var arrayname= [1,2,3,4,5];

now come in else case

if (arrayname.length === 0) {
  // do your stuff 
}else{
// doyour stuff
 }

now come in if case

 var arrayname= [];

if (arrayname.length === 0) {
  // do your stuff 
}else{
// doyour stuff
 }

for object

jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ test: "testvalue" }); // false

reference $.isEmptyObject and array length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM