11

I am trying to see if an option was selected in a selectbox and if not, I want it to alert a string. I was referring to this link(Check if option is selected with jQuery, if not select a default), but its not working.

Here's my code:

<select id="language" name="language">
  <option value=""></option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

if(!$("#language option:selected").length) {
  alert('no option is selected');
}

I pretty much copied the linked answer, but it's still not working. What am I missing?

Artemis
  • 2,553
  • 7
  • 21
  • 36
zeckdude
  • 15,877
  • 43
  • 139
  • 187

5 Answers5

19

Another way to go is:

  if($("#language").attr("selectedIndex") == 0) {
    alert("You haven't selected anything!");
   }

Working example at: http://jsbin.com/eluki3/edit

Erik
  • 20,526
  • 8
  • 45
  • 76
8

perhaps because the first one is selected by default.

try using

if($('#language :selected').text() == ''){
   alert('no option is selected');
}
Josh
  • 6,256
  • 2
  • 37
  • 56
4
if ( $("#language option:selected").val() === "" )
{
    alert("No items selected");
}

or simply

if ( $("#language").val() === "" )
{
    alert("No items selected");
}
rahul
  • 184,426
  • 49
  • 232
  • 263
  • Need to be careful if the HTML is ` – Brian Hogg Sep 19 '11 at 22:34
1

I solved the same issue using:

if ($('#mySelector option:selected').get().length>0) {
    //code
} else ...
Capensis
  • 113
  • 1
  • 9
0

Have you put the jQuery code inside a

$(function() { });

?

It needs to be evaluated after the DOM is ready.

Ed James
  • 10,385
  • 16
  • 71
  • 103