Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if no option is selected in a selectbox using jQuery?

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?

like image 738
zeckdude Avatar asked Mar 05 '10 10:03

zeckdude


1 Answers

Another way to go is:

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

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

like image 58
Erik Avatar answered Sep 27 '22 23:09

Erik