[英]How do I get all select elements that do not have an option selected using jQuery?
How do I get all select elements that do not have an option selected using jQuery?如何获取所有没有使用 jQuery 选择选项的选择元素?
<select id="one">
<option value=""></option>
<option value="test"></option>
</select>
<select id="two">
<option value=""></option>
<option selected value="test"></option>
</select>
What would the jQuery selector be that would return just #one based on no selection?什么 jQuery 选择器会根据没有选择只返回 #one?
Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")如果您的情况与 OP 不相似,请参阅https://stackoverflow.com/a/63588880/3499595 (默认值为“”)
$('select option:selected[value=""]').parent()
:selected
options of all the select
elementsselect
元素的所有:selected
选项""
, which in your case means no option is actually selected.""
,在您的情况下,这意味着实际上没有选择任何选项。select
)select
)You can take advantage of jQuery's .parent()
and .not()
functions.您可以利用 jQuery 的
.parent()
和.parent()
.not()
函数。 See below:见下文:
// selector for all 'select' elements with any option below it
var all = $("select>option").parent(); // alternative $("select")
// selector for all 'select' element with a selected child
var selected = $("select>option[selected]").parent();
// the subtraction set "all - selected" achieved by `not`.
var unselected = all.not(selected);
Note that jQuery's parent
takes care of removing duplicates from a set of parents of child elements.请注意,jQuery 的
parent
元素负责从一组子元素的父元素中删除重复项。
The accepted answer gives all select
elements with a selected option whose value is empty( ""
), which does answer the question in regard to the OP's sample HTML, where options with empty values are given, but it doesn't really answer the title question.接受的答案为所有
select
元素提供了一个值为空的选定选项( ""
),它确实回答了关于 OP 示例 HTML 的问题,其中给出了具有空值的选项,但它并没有真正回答标题问题。
There is a difference between selecting an option with an empty value, and not selecting any option at all.选择一个空值的选项和根本不选择任何选项是有区别的。
To select all select
elements with no option selected, use要选择没有选择任何选项的所有
select
元素,请使用
$('select').not(':has(option:selected)')
如果您有 jquery 库,请尝试
$('select option').filter(function(i,d){return !d.hasAttribute("selected")});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.