13

How to tell if a drop down has options to select?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 1
    I assume it is your fervent hope that nobody forget about the possibility that individual ` – Pointy Jan 31 '11 at 19:45

7 Answers7

15
var menu = getElementById("select_id");
if(menu.options.length) {
    // has children
} else {
    // empty
}
Makram Saleh
  • 8,613
  • 4
  • 27
  • 44
10
if ($("#myselect option").length > 0) {
  // Yay we have options
}
jessegavin
  • 74,067
  • 28
  • 136
  • 164
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
}

http://api.jquery.com/enabled-selector/

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
  • Sometimes I wonder whether anybody ever uses `` - it's one of those tags that I sometimes completely forget about, for months at a time ... – Pointy Jan 31 '11 at 21:41
  • 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