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

时间:2016-09-13 07:33:43

标签: javascript jquery html html-select

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

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

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

试试这个。获取select的值并检查它是否为null,如果不是则增加计数。

&#13;
&#13;
$(function(){
    $('#btn').click(function(){
    var count = 0;

    $('select').each(function(){
      
    if($(this).val() != null){
       count ++; 
     }
     
  })
    if(count == 4) {
      console.log('all selected');
    }
  })
  
})
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这对我有用

            var count = 0;
            $("select").each(function() {
                if(this.value === ''){
                    count++
                }
            });
            if (count === 0) {
                // all select boxes has selected option 
            }