如何使用jQuery检查选择框中是否没有选择任何选项?
问题描述:
我正在尝试查看在选择框中是否选择了一个选项,如果不是,我希望它提醒一个字符串。我指的是这个链接(检查如果选择了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.
这是我的代码:
<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?
答
另一种方法是:
if($("#language").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
}