2016-09-13 143 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。這是我身邊的一個愚蠢的錯誤。我編輯了代碼 –

相關問題