2014-01-28 524 views
0

嗯,我正在試圖建立一個單選按鈕組的網頁。我正在使用jquery來檢查是否所有的單選按鈕都被選中。這裏是代碼:如何檢查所有單選按鈕是否被選中?

<body> 
<p class="Cal">Welcome,</p> 
<hr /> 
<p class="Radio1">Answer the questions below. You will find the results after clicking 'Check my score'.</p> 
<hr /> 
<form method="post"> 
<p class="Question">1. Do you sleep early at night? (Anywhere around 9-10pm)</p> 
<p> 
<label> 
    <span class="Radio"> 
    <input type="radio" name="RadioGroup1" value="Yes" id="RadioGroup1_0" /> 
</span></label> 
<span class="Radio"> Yes 
<br /> 
<label> 
    <input type="radio" name="RadioGroup1" value="No" id="RadioGroup1_1" /> 
    No 
</label> 
<br /> 
<label> 
    <input type="radio" name="RadioGroup1" value="Sometimes" id="RadioGroup1_2" /> 
    Sometimes </label> 
</span><br /> 
</p> 
<p class="Question">2. Do you wake up early in morning?(Anywhere around 5-7am)</p> 
<p> 
<label> 
    <span class="Radio"> 
    <input type="radio" name="RadioGroup2" value="Yes" id="RadioGroup2_0" /> 
    Yes  </span></label> 
<span class="Radio"><br /> 
    <label> 
    <input type="radio" name="RadioGroup2" value="No" id="RadioGroup2_1" /> 
    No 
</label> 
<br /> 
<label> 
    <input type="radio" name="RadioGroup2" value="Sometimes" id="RadioGroup2_2" /> 
    Sometimes 
</label> 
</span><br /> 
</p><input type="submit" value="Check my score" /></form></body> 

那麼有30個這樣的問題。而我的jQuery代碼如下:

$(document).on('submit', 'form', function() { 
var validate = true; 
var unanswered = new Array(); 

// Loop through available sets 
$('.Radio').each(function() { 
    // Question text 
    var Question = $(this).prev().text(); 
    // Validate 
    if (!$(this).find('input').is(':checked')) { 
     // Didn't validate ... dispaly alert or do something 
     unanswered.push(Question); 

     validate = false; 
    } 
}); 

if (unanswered.length > 0) { 
    msg = "Please answer the following questions:\n" + unanswered.join('\n'); 
    alert(msg); 
} 
else{ 
    msg = "Done!"; 
    alert(msg); 
} 
return validate; 
}); 

現在我試着盡一切可能使這項工作。但即使在我檢查每個答案的單選按鈕之後,我仍然會彈出「請回答以下問題:」然後列出一個空白列表。我從來沒有收到「完成!」的消息即使所有問題的答案都被檢查。 故障在哪裏?

+0

它是不可能對所有的單選按鈕的單選按鈕組內進行檢查。你是否確實意味着你想檢查每個組中至少有一個單選按鈕被選中? – crush

+0

可能重複[如何檢查每個組中的單選按鈕是否在jQuery中檢查?](http://stackoverflow.com/questions/3553197/how-to-check-if-a-radio-button-in-每個組都在jquery中檢查) –

+0

可能的重複[確定是否每個無線電組選擇了一個選項](http://stackoverflow.com/questions/6796870/determine-if-every-radio-group都具有一個-有-的選項選擇的) – j08691

回答

0

您可以使用HTML5 required屬性,這是更好的選擇。 您還可以使用JavaScript的循環,並檢索每個單選按鈕組的值,使用

$("input:radio[name=radiogroupX]:checked") 
相關問題