2016-09-13 140 views
1

我有7个简单的选择框:如何检查所有选择框是否使用jQuery选择了选项?

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

如何检查是否所有的选择框有选择的,而不是默认选项的东西吗?

+0

哪里是期权价值? – yash

+0

设置'select'输入的'value'值....如果未指定value属性,'text'将被视为'value' .. – Rayon

+0

您可以通过多种方式获取Element,例如'document .getElemnetById('HTMLidAttribute')'那么它可以像测试'Element.selected'一样简单。 – PHPglue

回答

3

如果长度== 0,则没有默认元素被选中,您可以找到被禁用的选项。

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

@nnnnnn:是的。我将首先记录错误,然后更改文本。谢谢:) –

0

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

$(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>

+0

这不起作用 - 你需要在事件处理程序中移动var count = 0; * *。 – nnnnnn

+0

谢谢@nnnnnn。这是我身边的一个愚蠢的错误。我编辑了代码 –

相关问题