I am writing a webpage to display a small quiz, below is the code of the
webpage. I used a for loop so that if there are a lot of questions, it would
reduce the code. but the line ----
document.getElementById('id[i]').firstChild.data = 'CORRECT'; ---- doesn't
work with the ('id[i]') part. if i use ('id[0]') it works. the ans[i] works
too. is it something to do with calling the id from an array. how can i
solve this problem and keeping the for loop.
<HTML>
<HEAD>
<SCRIPT language = 'Javascript'>
var ans = new Array('0','0');
var correctans = new Array('4','2');
var correctansstring = new Array('4','6');
var id = new Array('id1','id2');
function check()
{
for(i = 0; i < 2; i++)
{
if(ans[i] == correctans[i])
{
document.getElementById('id[i]').firstChild.data = 'CORRECT';
document.getElementById('id[i]').style.color = 'green';
}
else
{
document.getElementById('id[i]').firstChild.data = 'WRONG\nThe correct
answer is: '+correctansstring[i];
document.getElementById('id[i]').style.color = 'red';
}
}
}
</SCRIPT>
</HEAD>
<BODY>
1. What is 2 + 2?<BR>
<INPUT type = 'radio' name = 'q1' onClick = 'ans[0] = 1'> 1<BR>
<INPUT type = 'radio' name = 'q1' onClick = 'ans[0] = 2'> 2<BR>
<INPUT type = 'radio' name = 'q1' onClick = 'ans[0] = 3'> 3<BR>
<INPUT type = 'radio' name = 'q1' onClick = 'ans[0] = 4'> 4<BR>
<a id=id[0]> </a>
<BR>
1. What is 3 + 3?<BR>
<INPUT type = 'radio' name = 'q2' onClick = 'ans[1] = 1'> 5<BR>
<INPUT type = 'radio' name = 'q2' onClick = 'ans[1] = 2'> 6<BR>
<INPUT type = 'radio' name = 'q2' onClick = 'ans[1] = 3'> 7<BR>
<INPUT type = 'radio' name = 'q2' onClick = 'ans[1] = 4'> 8<BR>
<a id=id[0]> </a>
<BR>
<INPUT type = 'button' value = 'CHECK' onClick = 'check()'><BR>
</BODY>
</HTML>