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
3 Answers 3
Use the isEmptyObject method
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false
answered Oct 17, 2013 at 11:53
Comments
answered Oct 17, 2013 at 11:55
Vinay Pratap Singh Bhadauria Vinay Pratap Singh Bhadauria
9,9773 gold badges30 silver badges50 bronze badges
Comments
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
Meules
Ok thx, never heard of this. I've read the references but how do I incorporate this in the code above?
Rituraj ratan
first $('.zoeken-select.listA').fadeIn(300); chnage this to $('.zoeken-select .listA').fadeIn(300);
lang-js
$(this).val()
containscategory
in this example (surrendering[{value: "1234", text: "Test" }]
)?