View Full Version : Loop Validation Of Radio Buttons?

04-20-2005, 03:08 AM

I have a survey with 20 questions, each question has 4 options (radio buttons)...

I am looking to validate that each question has been answered, and if a question has not been answered alert the user which specific question they need to complete.

Example Of Question setup:

<h4>Question 1 ..............</h4>
<input name="q1" type="radio" value="1">
<input name="q1" type="radio" value="2">
<input name="q1" type="radio" value="3">
<input name="q1" type="radio" value="4">

<h4>Question 2 ..............</h4>
<input name="q2" type="radio" value="1">
<input name="q2" type="radio" value="2">
<input name="q2" type="radio" value="3">
<input name="q2" type="radio" value="4">

I have tried a loop similar to this:

for (i=0; i >= 20; i++)
if (formObject.qi.checked == false)
message+="\n - Question" + i + "must be answered";

But this does not work.... How do I put the i in if statement, so that it is recognised as the loop parameter, rather than just a i???

Anyhelp would be great, I just want to make the programming a little better than individually going through each question.


04-20-2005, 03:13 AM
Just specify a default value. Easier and works with Javascript disabled.

04-20-2005, 04:35 AM
But these are survey or quiz-type questions. Setting default values is not appropriate.

function isChecked(radGroup){
for (var i=0;i<radGroup.length;i++){
if (radGroup[i].checked) return true;
return false;
And then in your validation script:

for (var i=1; i <= 20; i++)
if (!isChecked(formObject.elements["q"+i]))
message+="\n - Question" + i + " must be answered";