JS / Jquery:如何检查下拉菜单中是否选择了值? [英] JS/Jquery: how to check whether dropdown has selected values?

查看:186
本文介绍了JS / Jquery:如何检查下拉菜单中是否选择了值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经google了,尝试了一些方法来做到这一点,但到目前为止我都没有办法。我正在寻找的是非常简单的:我想要能够知道一个下拉列表是否具有选定的值。问题是selectedIndex,:selected,val()等会为以下情况返回结果:

I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:

<select>
<option value="123">123</option>
<option value="234">234</option>
</select>

显然,浏览器将显示123选项的下拉列表,但只有在没有其他选项,实际上这个下拉列表没有选定的值,因为没有selected属性。所以基本上我试图找出如何从这一个分解上面的下拉列表

Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one

<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>


推荐答案

var hasValue = ($('select > [selected]').length > 0);

或者,

var hasValue = $('select').has('[selected]');

这篇关于JS / Jquery:如何检查下拉菜单中是否选择了值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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