如何使用jQuery检查选择框中是否没有选择任何选项? [英] How do I check if no option is selected in a selectbox using jQuery?

查看:144
本文介绍了如何使用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!");
   }

工作示例: http://jsbin.com/eluki3/edit

这篇关于如何使用jQuery检查选择框中是否没有选择任何选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆