View Full Version : Looping through a form

05-02-2006, 04:29 AM
Hey there,
I'm working with a dynamically generated form, basically a quiz type of little mini-app.

In the form, the radio buttons are named like:

Question 1...
<input type="radio" name="question1" ../>Answer 1...
<input type="radio" name="question1" ../>Answer 2...
<input type="radio" name="question1 ../>Answer 3..
Question 2..
<input type="radio" name="question2" ../>Answer 1..
<input type="radio" name="question2" ../>Answer 2..

I am "grading" the form via Javascript as it is a necessity that this is a standalone page with no serverside input (will be run on a machine without internet access).

I know how many questions there will be, but it changes depending on which quiz they are taking. So I am wondering how to loop through the question_ inputs..

If I need to be a little more clear please let me know.

Thanks in advance,

05-02-2006, 06:39 AM
See if this is something that may work for you:

JavaScript code:
var question = [["What is question 1?","Answer 1","Answer 2","Answer 3",1],
["Is this question 2?","Answer 1","Answer 2","Answer 3","Answer 4",2],
["How about question 3?","Answer 1","Answer 2",3] ];

function showQuestions() {
var strHTML = "";
for (i = 0; i < question.length; i++) {
strHTML += question[i][0] + '<br/>';
for (j = 1; j < question[i].length - 1; j++) {
strHTML += '<input type="radio" name="question' + (i + 1) + '" value="' + j + '" />';
strHTML += question[i][j] + '<br/>';
strHTML += '<br/>';

document.getElementById('question_section').innerHTML = strHTML;

HTML code:
<script type="text/javascript" src="ques.js"></script>
<body onload="showQuestions();">
<div id="question_section"></div>

This uses an array to store all the information, including answers, and will loop through printing all the questions, radio boxes, and answers. If you have any questions, or this isn't quite what you're looking for, let me know.