多个单选按钮组的客户端验证

时间:2010-01-23 15:43:01

标签: .net radiobuttonlist

这是我的代码:

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

如何用变量替换我的代码中的'group [x]',所以三个for循环被替换为一个(因为实际上还有更多的问题和答案)?

1 个答案:

答案 0 :(得分:1)

JavaScript有一个很好的东西,它允许您作为对象中的数组访问成员:

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
    }
}