I would like to know how to check if an array is empty or null in jQuery. I tried array.length === 0
but it didn't work. It did not throw any error either.
This is the code:
var album_text = new Array();
$("input[name='album_text[]']").each(function(){
if( $(this).val() && $(this).val() != '') {
album_text.push($(this).val());
}
});
if (album_text.length === 0) {
$('#error_message').html("Error");
}
else {
// send data
}
You should check for
''
(empty string) before pushing into your array. Your array has elements that are empty strings. Then youralbum_text.length === 0
will work just fine.User JQuery is EmptyObject to check whether array is contains elements or not.
As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.
Some notes on what you were doing and what I changed.
$(this)
is always a valid jQuery object so there's no reason to ever checkif ($(this))
. It may not have any DOM objects inside it, but you can check that with$(this).length
if you need to, but that is not necessary here because the.each()
loop wouldn't run if there were no items so$(this)
inside your.each()
loop will always be something.[]
rather thannew Array()
.if (value)
when value is expected to be a string will both protect fromvalue == null
,value == undefined
andvalue == ""
so you don't have to doif (value && (value != ""))
. You can just do:if (value)
to check for all three empty conditions.if (album_text.length === 0)
will tell you if the array is empty as long as it is a valid, initialized array (which it is here).What are you trying to do with this selector
$("input[name='album_text[]']")
?I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.
In the isEmptyObject doc, it mentions:
which you can determine by
$.isPlainObject
. The return of$.isPlainObject([])
is false.