0

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>
Stéphane Bruckert
23.1k14 gold badges102 silver badges136 bronze badges
asked Oct 17, 2013 at 11:52
1
  • I assume $(this).val() contains category in this example (surrendering [{value: "1234", text: "Test" }])? Commented Oct 17, 2013 at 11:54

3 Answers 3

1

Use the isEmptyObject method

jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false
answered Oct 17, 2013 at 11:53

Comments

0

use

jQuery.isEmptyObject({});

see EmptyObject

answered Oct 17, 2013 at 11:55

Comments

0

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

answered Oct 17, 2013 at 11:55

2 Comments

Ok thx, never heard of this. I've read the references but how do I incorporate this in the code above?
first $('.zoeken-select.listA').fadeIn(300); chnage this to $('.zoeken-select .listA').fadeIn(300);

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.