繁体   English   中英

如何使用jquery检查所有选择框是否都选择了选项?

[英]How to check if all select boxes has selected option using jquery?

我有 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>

如何检查所有选择框是否都选择了某些内容而不是默认选项?

您可以找到已禁用的选定选项,如果 length==0 则不选择默认元素。

if($('option[disabled]:selected').length == 0){
   // ALL the select boxes have something selected rather than the default option
}

尝试这个。 获取 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>

这对我有用

            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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM