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