循环通过单选按钮,然后将总数相加
嗨,
希望有人可以帮助,我需要能够保持一个运行的单选按钮选定的总数,作为一个用户通过一组16个问题,分为4个目录,然后在"提交"有总数量显示在屏幕上,或"提交"循环通过选定的单选按钮和得到总数.
我现在所拥有的将遍历所有按钮,然后将所有总数相加,我如何才能让此代码仅将"选中"按钮相加在一起?
谢谢艾伦:)
选择 | 换行 | 行号
- ..
- <script type="text/javascript">
- function showTotal(form, totalEl)
- {
- var el, els = form.elements;
- var sum = 0;
- for (var i=0, num=els.length; i<num; ++i){
- el = els[i];
- // need to only add up checked radio buttons?
- if ('radio' == el.type && /SumB/.test(el.name)){
- sum += +el.value;
- }
- form.elements[totalEl].value = sum;
- }
- }
- </script>
- </head>
- <body>
- <form action=""><div>
- First set of questions:<br>
- Question group 1: <input type="radio" name="SumB_myquestion1" value="5" checked><br>
- Question group 1: <input type="radio" name="SumB_myquestion1" value="10"><br>
- Question group 1: <input type="radio" name="SumB_myquestion1" value="15"><br>
- Question group 1: <input type="radio" name="SumB_myquestion1" value="20"><br>
- <br>
- Second set of questions:<br>
- Question group 2: <input type="radio" name="SumB_myquestion2" value="5" checked><br>
- Question group 2: <input type="radio" name="SumB_myquestion2" value="10"><br>
- Question group 2: <input type="radio" name="SumB_myquestion2" value="15"><br>
- Question group 2: <input type="radio" name="SumB_myquestion2" value="20"><br>
- <br>
- <input type="button" value="Show total" onclick="showTotal(this.form, 'formTotal');">
- <br>
- <br>
- <input type="text" name="formTotal" readonly size="20"> is your score.<br>
- <br>
- </div></form>
- ..