[英]How to check if all select boxes has selected option using jquery?
I have 7 simple select boxes:我有 7 个简单的选择框:
<select>
<option selected disabled>choose something</option>
<option>some text</option>
<option>some more text</option>
<option>and more and more</option>
</select>
<select>
<option selected disabled>choose something</option>
<option>some text</option>
<option>some more text</option>
<option>and more and more</option>
</select>
<select>
<option selected disabled>choose something</option>
<option>some text</option>
<option>some more text</option>
<option>and more and more</option>
</select>
<select>
<option selected disabled>choose something</option>
<option>some text</option>
<option>some more text</option>
<option>and more and more</option>
</select>
How can I check if ALL the select boxes have something selected rather than the default option?如何检查所有选择框是否都选择了某些内容而不是默认选项?
You can find selected option that are disabled, if length==0 then no default element are selected.您可以找到已禁用的选定选项,如果 length==0 则不选择默认元素。
if($('option[disabled]:selected').length == 0){
// ALL the select boxes have something selected rather than the default option
}
Try this.尝试这个。 Get value of select and check if its null and increment the count if its not.
获取 select 的值并检查它是否为空,如果不是则增加计数。
$(function(){ $('#btn').click(function(){ var count = 0; $('select').each(function(){ if($(this).val() != null){ count ++; } }) if(count == 4) { console.log('all selected'); } }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option selected disabled>choose something</option> <option>some text</option> <option>some more text</option> <option>and more and more</option> </select> <select> <option selected disabled>choose something</option> <option>some text</option> <option>some more text</option> <option>and more and more</option> </select> <select> <option selected disabled>choose something</option> <option>some text</option> <option>some more text</option> <option>and more and more</option> </select> <select> <option selected disabled>choose something</option> <option>some text</option> <option>some more text</option> <option>and more and more</option> </select> <button id="btn">Check</button>
This works for me这对我有用
var count = 0;
$("select").each(function() {
if(this.value === ''){
count++
}
});
if (count === 0) {
// all select boxes has selected option
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.