如何使用 jQuery 检查是否在选择框中未选择任何选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2385963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if no option is selected in a selectbox using jQuery?
提问by zeckdude
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.
我试图查看是否在选择框中选择了一个选项,如果没有,我希望它提醒一个字符串。我指的是这个链接(检查是否使用 jQuery 选择了选项,如果没有选择默认值),但它不起作用。
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?
我几乎复制了链接的答案,但它仍然无法正常工作。我错过了什么?
回答by Erik
Another way to go is:
另一种方法是:
if($("#language").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
}
Working example at: http://jsbin.com/eluki3/edit
工作示例:http: //jsbin.com/eluki3/edit
回答by Josh
perhaps because the first one is selected by default.
可能是因为默认选择了第一个。
try using
尝试使用
if($('#language :selected').text() == ''){
alert('no option is selected');
}
回答by rahul
if ( $("#language option:selected").val() === "" )
{
alert("No items selected");
}
or simply
或者干脆
if ( $("#language").val() === "" )
{
alert("No items selected");
}
回答by Ed James
Have you put the jQuery code inside a
你有没有把 jQuery 代码放在一个
$(function() { });
$(function() { });
?
?
It needs to be evaluated after the DOM is ready.
需要在 DOM 准备好后进行评估。
回答by Capensis
I solved the same issue using:
我使用以下方法解决了同样的问题:
if ($('#mySelector option:selected').get().length>0) {
//code
} else ...