How to tell if a drop down has options to select?
Asked
Active
Viewed 1.6k times
13
-
1I assume it is your fervent hope that nobody forget about the possibility that individual ` – Pointy Jan 31 '11 at 19:45
7 Answers
15
var menu = getElementById("select_id");
if(menu.options.length) {
// has children
} else {
// empty
}

Makram Saleh
- 8,613
- 4
- 27
- 44
-
2Yes, this is the correct answer, assuming OP is not using jQuery. – Daniel Williams Sep 04 '18 at 22:50
10
if ($("#myselect option").length > 0) {
// Yay we have options
}

jessegavin
- 74,067
- 28
- 136
- 164
-
-
-
Kevin Bacon turns into a robot! Just kidding @Pablo. I fixed my answer. Good catch. – jessegavin Feb 01 '11 at 01:13
-
2"There are 2 hard problems in computer science: caching, naming, and off-by-1 errors" – Pablo Fernandez Feb 01 '11 at 02:08
8
var hasOptions = !!$('#theSelect option').filter(function() { return !this.disabled; }).length;
maybe? This looks for <option>
elements that are not disabled.

Pointy
- 405,095
- 59
- 585
- 614
3
$('#input1 option').length > 0
Where #input
is the ID of the select
element you are running this test against.

Scott
- 13,735
- 20
- 94
- 152
2
if ($("#myselect option:enabled").length){
// Yay!
}else{
// Oh, no available options
}

Phrogz
- 296,393
- 112
- 651
- 745
0
Native javascript solution:
!!document.getElementById('jiveviewthreadsform-filter').children.length
(Please do not overuse jQuery, thanks)

Pablo Fernandez
- 103,170
- 56
- 192
- 232
-
@Pointy True but the OP never said anything about `
`. +1 to your solution anyway, it's the best one (though a bit verbose) – Pablo Fernandez Jan 31 '11 at 21:39 -
-
How is this "overuseing" jquery? It's a simple operation that doesn't really put any significant overhead. – Train Nov 20 '18 at 20:31
0
Very hackily, you can just check its selectedIndex; since most browsers ensure that there is something selected if at all possible, it will only be -1 if there are no selectable options.

Neil
- 54,642
- 8
- 60
- 72