JS/Jquery:如何检查下拉列表是否已选择值?
我已经用谷歌搜索并尝试了多种方法来做到这一点,但到目前为止没有一个对我有用。我正在寻找的东西非常简单:我希望能够判断下拉列表是否具有选定的值。问题是 selectedIndex、:selected、val() 等确实会返回以下情况的结果:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>
显然,浏览器将显示此下拉列表,其中选择了 123 选项,但它只会被选择,因为没有其他选项,实际上,这个下拉列表没有选定的值,因为没有“选定”属性。所以基本上我想找到如何区分上面的下拉列表和这个下拉列表
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者,
Alternatively,
快速解决方案:
然后查看是否有
.val()
Quick solution:
Then see if you have a
.val()
批准的答案似乎对我不起作用。
以下是我检查是否选择了所有选择选项的方法:
The approved answer doesn't seem to work for me.
Here is how I do it to check if all select options are selected:
据我所知,您的两个示例之间没有功能区别。本质上,浏览器会自动选择第一个
选项
。例如,请参阅
第一个示例的结果。
如果您确实想防止这种情况发生,您有两种选择。第一个是根据 Jason 的回答,在
select
中引入一个新的空元素。另一个选项是取消选择自动选择的值:这将清除选择。因此,任何非空字符串的
$('select').val()
结果都将是用户所做的更改。As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first
option
.See, for example, the result of
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:This clears the selection. Any result of
$('select').val()
that isn't an empty string will therefore be a change by the user.