This is my javascript:
<script type="text/javascript">
var crct_answrs = new Array(<?php echo implode(',', $crct_ans); ?>);
var answrs = new Array();
function check_ans(){
for(var i = 1; i < 11; i++){
var tst = "ques"+i;
var radio = document.getElementsByName(tst);
for (var x = 0; x < radio.length; x ++) {
if (radio[x].checked) {
answrs = radio.value;
}
}
}
}
</script>
This is part of HTML:
<form>
<div id="quest1" class="question">
<div class="prblm">
<?php echo $questions[1]; ?></div>
<table class="answrs">
<tr>
<td><?php echo $answrs[1][1]; ?></td>
<td><input name="ques1" type="radio" value="1"></td>
</tr>
<tr>
<td><?php echo $answrs[1][2]; ?></td>
<td><input name="ques1" type="radio" value="2"></td>
</tr>
<tr>
<td><?php echo $answrs[1][3]; ?></td>
<td><input name="ques1" type="radio" value="3"></td>
</tr>
<tr>
<td><?php echo $answrs[1][4]; ?></td>
<td><input name="ques1" type="radio" value="4"></td>
</tr>
</table>
</div>
I have 10 same pattern div tags with tables and the input name is change accordingly.
check_ans() runs on onclick. But all the time getElementsByName returns undefined. Why this happens. Please help me. Thanks!
Your error lies in:
answrsis an array and needs to set values to the index of the corresponding iterator it’s on.radio.valueis trying to access value from theradioarray, but has left out it’s index as well. Look at my solution below for the fix:I’ve got a jsFiddle working.
JavaScript:
Output:
When selecting an answer 1, 2, 3, 4, 3, 2, 1, 2, 3, 4 for questions 1-10 the array is: