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]');