I am creating a test generator and have an array of textfields ("answer[]") created by a simple piece of PHP code. As you can see, I have radio buttons corresponding to each text field, which is a potential answer to a multi choice question. I already have working code which ensures that an answer is selected and not the default option. However, I also want to validate that when an answer is selected, the corresponding text field is not blank. I am having problems accessing the values of each text field in the array.
Here's the php/html code....
Expand|Select|Wrap|Line Numbers
- <p>
- Enter the answer options and ensure the radio button selected is the correct answer. <br/><br/>
- <?php
- //Generate form
- $count=5;
- $name=array("A","B","C","D","E");
- for ($i=0;$i<$count;$i++) {
- echo "<input type='radio' name='option' value='$i'>$name[$i] <input type='text' name='answer[$i]' size='80'><br/>";
- }
- ?>
- <input type="radio" name="option" value="No Answer" checked="checked" />No Answer selected
Expand|Select|Wrap|Line Numbers
- function validateCorrectAnswer(form){
- var error="";
- var none="No Answer";
- var ansText ="";
- var selected;
- for (var i=0; i<form.option.length; i++) {
- if (form.option[i].checked)
- {
- selected = form.option[i].value ;
- if (selected==none)
- error = "You didn't select a correct answer.\n";
- else if(form.elements['answer[i]'].value=="")
- error = "You didn't enter any text for the correct
- answer.\n";
- }
- }
- return error;
- }