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

青春壹個敷衍的年華 提交于 2019-11-30 23:56:17

问题


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?


回答1:


Another way to go is:

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

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




回答2:


perhaps because the first one is selected by default.

try using

if($('#language :selected').text() == ''){
   alert('no option is selected');
}



回答3:


if ( $("#language option:selected").val() === "" )
{
    alert("No items selected");
}

or simply

if ( $("#language").val() === "" )
{
    alert("No items selected");
}



回答4:


Have you put the jQuery code inside a

$(function() { });

?

It needs to be evaluated after the DOM is ready.




回答5:


I solved the same issue using:

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


来源:https://stackoverflow.com/questions/2385963/how-do-i-check-if-no-option-is-selected-in-a-selectbox-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!