Javascript JS/Jquery:如何检查下拉列表是否已选择值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4018365/
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
JS/Jquery: how to check whether dropdown has selected values?
提问by Eugene
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:
我已经用谷歌搜索并尝试了多种方法来做到这一点,但到目前为止都没有对我有用。我正在寻找的东西非常简单:我希望能够判断下拉列表是否具有选定的值。问题是 selectedIndex、:selected、val() 等确实会返回以下情况的结果:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>
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
显然,浏览器会显示这个下拉列表,其中 123 选项被选中,但它只会被选中,因为没有其他选项,实际上这个下拉列表没有选定的值,因为没有“selected”属性。所以基本上我试图找到如何区分上面的下拉菜单和这个下拉菜单
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
回答by John Strickler
var hasValue = ($('select > [selected]').length > 0);
Alternatively,
或者,
var hasValue = $('select').has('[selected]');
回答by Jason
Quick solution:
快速解决方案:
<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>
Then see if you have a .val()
然后看看你有没有 .val()
回答by JasonP
The approved answer doesn't seem to work for me.
批准的答案似乎对我不起作用。
Here is how I do it to check if all select options are selected:
这是我如何检查是否选择了所有选择选项:
if($('select option:selected').length > 0) {
/* Do your stuff here */
}
回答by lonesomeday
As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first option
.
据我所知,您的两个示例之间没有功能区别。本质上,浏览器会自动选择第一个option
.
See, for example, the result of
参见,例如,结果
$('option:selected')
on your first example.
在你的第一个例子中。
If you really want to prevent this happening, you have two options. The first is to introduce a new, empty element into the select
, per Jason's answer. The other option is to deselect the automatically selected value:
如果你真的想防止这种情况发生,你有两个选择。第一个是select
根据 Jason 的回答,在 中引入一个新的空元素。另一个选项是取消选择自动选择的值:
$(document).load(function(){
$('option:selected').attr('selected', false);
});
This clears the selection. Any result of $('select').val()
that isn't an empty string will therefore be a change by the user.
这将清除选择。因此,任何$('select').val()
不是空字符串的结果都将是用户的更改。
回答by code90
This should work:
这应该有效:
if($('#mySelect').find('[defaultSelected]').size()>0){/*do your stuff*/}