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

痞子三分冷 提交于 2019-12-01 03:48:07

Another way to go is:

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

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

perhaps because the first one is selected by default.

try using

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

or simply

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

Have you put the jQuery code inside a

$(function() { });

?

It needs to be evaluated after the DOM is ready.

I solved the same issue using:

if ($('#mySelector option:selected').get().length>0) {
    //code
} else ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!