2014-01-28 5 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; 
}); 

지금이 작업을 할 수있는 모든 방법을 시도했습니다. 그러나 각 답변마다 라디오 버튼을 체크 한 후에도 "계속해서 다음 질문에 답하십시오."라는 메시지가 나오고 빈 목록이 나옵니다. 나는 결코 "Done!"이라는 메시지를받지 못한다. 모든 질문에 대한 답을 확인하더라도. 오류가 어디 있습니까?

+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 -has-had-an-option-selected) – j08691

답변

0

더 나은 옵션 인 HTML5 required 속성을 사용할 수 있습니다. 또한

$("input:radio[name=radiogroupX]:checked") 
관련 문제