Client side validation of multiple radio buttons groups

Posted by absolutely-free on Stack Overflow See other posts from Stack Overflow or by absolutely-free
Published on 2010-01-23T15:43:01Z Indexed on 2010/03/20 17:01 UTC
Read the original article Hit count: 299

Filed under:
|

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) ?

© Stack Overflow or respective owner

Related posts about radiobuttonlist

Related posts about .NET