多个单选按钮组的客户端验证 [英] Client side validation of multiple radio buttons groups

查看:88
本文介绍了多个单选按钮组的客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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>

我怎么能代替'组[X]在我的code。通过一个变量,所以三个for循环接一个被替换(因为在现实中也有很多的问题和答案)?

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

推荐答案

有一个美妙的事情有关的JavaScript,可以让你访问成员的阵列中的一个对象:

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

这篇关于多个单选按钮组的客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆