2011-07-27 24 views
0

我有幾個問題的民意調查。下面是HTML代碼jquery驗證

<form id="pool"> 
<div class="questions> 
    <input type="radio" name="sex">Male 
    <input type="radio" name="sex">Female 
</div> 

<div class="questions> 
    <input type="radio" name="hair">Brown 
    <input type="radio" name="hair">Blonde 
</div> 

.... a lot of qestions div's 
</form> 

怎麼辦這樣的形式提交後,以確保有在所有div`s選中的單選按鈕?

+0

可能重複[確定是否每一個單選按鈕組已選擇一個選項](http://stackoverflow.com/questions/6796870/determine-if-every-radio-group-has-had-an-option-selected) – Paulpro

回答

1

如果你知道你有多少組有你可以做:

if($('#pool input:radio:checked').length < numGroups){ 
    // At least one group isn't checked 
} 

否則,你需要先計算組的數量。我想不出任何辦法做到這一點更好,然後:

var rgroups = []; 
$('#pool input:radio').each(function(index, el){ 
     var i; 
     for(i = 0; i < rgroups.length; i++) 
      if(rgroups[i] == $(el).attr('name')) 
       return true; 
     rgroups.push($(el).attr('name')); 
    } 
); 
rgroups = rgroups.length; 

if($('#pool input:radio:checked').length < rgroups) 
    alert('You must fill in all the fields.'); 
else 
    alert('Thanks!'); 
0

設置默認值或創建提交按鈕,並檢查是否檢查了一些值。如果沒有無線電按鈕被選中,顯示錯誤消息,並且不提交表單(返回false)

0

未經測試的代碼,但是這是想法:

if($('#pool').children().length == $('pool 
div').find('#pool input:radio:selected').length) { 
//do stuff 
}