Reputation: 17475
What is a safe way to check that a listbox is empty in JQuery ? Alternative question, how to check if there is no item actively selected ?
I have tried :
if(... .val() != "null")
also
if(... .val() != null)
as I spotted null
value on val()
while debugging when the list is empty or nothing is selected, but doesn't seem to work accurately.
Upvotes: 0
Views: 5601
Reputation: 194
best to use
$('select#myselect option').length;
or
$(myselct).find('option').length;
to get the length
ex:
var x = $(myselct).find('option').length;
if (x > 0){'if listbox contains items}
Upvotes: 1
Reputation: 557
tests if any item is selected. if true, an item is selected and will display the slected value.
if($("#Select").val() != null){
alert($("#Select").val());
}
tests if any item is not selected . if true is no items are selected
if($("#Select").val() == null){
alert("no items selected.);
}
Upvotes: 0
Reputation: 76003
To check if there are <option>
elements inside the <select>
element:
if ($('#my-select').children().length == 0) {
alert('OH NO, there aren\'t any options to select!');
}
To check to see if an <option>
inside the <select>
has been selected (only works if selected <option>
element has a value
attribute)
if (typeof($('select').children(':checked').val()) == 'undefined') {
alert('No Option with a Value Selected');
}
Here is a demo: http://jsfiddle.net/sJdBJ/
Some Docs:
typeof()
: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof.children()
: http://api.jquery.com/children.length
: http://api.jquery.com/lengthUpvotes: 5
Reputation: 35832
I usually use pure JavaScript for this:
$('#select-id')[0].selectedIndex == -1;
Please note that $('#select-id')[0]
converts back the jQuery object to JavaScript object.
Upvotes: 1