views:

217

answers:

1

This is my code:

<html> 
<head> 
<title>scoreboard</title> 
<script> 
function calculate() { 
var sum=0; var total=0; 

for (var i=0; i < document.questions.group1.length; i++){ 
   if (document.questions.group1[i].checked){ 
      sum = parseInt(document.questions.group1[i].value) 
         total = parseInt(total + sum);}} 

for (var i=0; i < document.questions.group2.length; i++){ 
   if (document.questions.group2[i].checked){ 
      sum = parseInt(document.questions.group2[i].value) 
         total = parseInt(total + sum);}} 

for (var i=0; i < document.questions.group3.length; i++){ 
   if (document.questions.group3[i].checked){ 
      sum = parseInt(document.questions.group3[i].value) 
         total = parseInt(total + sum);}} 

alert(total) 
} 
</script> 
</head> 
<body> 
<form name="questions"> 
A:<br> 
answer a1: <input type="radio" name="group1" value="0"> 
answer a2: <input type="radio" name="group1" value="1"> 
answer a3: <input type="radio" name="group1" value="2"> 
answer a4: <input type="radio" name="group1" value="3"><br> 
B:<br> 
answer b1: <input type="radio" name="group2" value="0"> 
answer b2: <input type="radio" name="group2" value="1"> 
answer b3: <input type="radio" name="group2" value="2"> 
answer b4: <input type="radio" name="group2" value="3"><br> 
C:<br> 
answer c1: <input type="radio" name="group3" value="0"> 
answer c2: <input type="radio" name="group3" value="1"> 
answer c3: <input type="radio" name="group3" value="2"> 
answer c4: <input type="radio" name="group3" value="3"><br><br>

<input type="button" value="total" onclick="calculate()"> 
</form> 
</body> 
</html>

How can I replace 'group[x]' in my code by a variable, so the three for-loops are replaced by one (because in reality there are a lot more questions and answers) ?

A: 

There is a neat thing about JavaScript that lets you access members as an array in an object:

var q = document.questions;
var totalQuestions = 3;
var total = 0;

for(var i = 1; i <= totalQuestions; i++) {
    var ans = q["group" + i];
    var checked = false;
    for(var j = 0; j < ans.length; j++) {
        if(ans[j].checked) {
            checked = true;
            var sum = parseInt(ans[j].value);
            total = total + sum;
        }
    }
    if(!checked) {
        // no answer checked: show error here
    }
}
Pindatjuh
Perfect! Thank you very much.Do you know how to insert a warning in this script if not every group is checked too?Much obliged.