使用单选按钮的输入计算分数

时间:2016-03-05 15:35:39

标签: javascript html

我想使用函数check()并通过它传递单选按钮的名称,以便注册所有按钮的输入。但似乎我无法使用onclick html属性传递任何内容。我打算添加更多问题,所以我需要一种方法来轻松使用check()函数。

<div class="questionCard" id="q1">
                <p>Each problem consists of three statements. Based on the first two statements, the third statement may be true, false, or uncertain.</br></br>
                1.</br>
                Tanya is older than Eric.</br>
                Cliff is older than Tanya.</br>
                Eric is older than Cliff.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a1" onclick="check(a1)" value="true"/>True
                <input type="radio" name="a1" onclick="check(a1)" value="false"/>False
                <input type="radio" name="a1" onclick="check(a1)" value="uncertain"/>Uncertain
            </div>
            <div class="questionCard" id="q2">
                <p>
                2.</br>
                Blueberries cost more than strawberries.</br>
                Blueberries cost less than raspberries.</br>
                Raspberries cost more than strawberries and blueberries.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a2" value="true"/>True
                <input type="radio" name="a2" value="false"/>False
                <input type="radio" name="a2" value="uncertain"/>Uncertain
            </div>
            <div class="questionCard" id="q3">
                <p>
                3.</br>
                All the trees in the park are flowering trees.</br>
                Some of the trees in the park are dogwoods.</br>
                All dogwoods in the park are flowering trees.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a3" value="true"/>True
                <input type="radio" name="a3" value="false"/>False
                <input type="radio" name="a3" value="uncertain"/>Uncertain
            </div>

这是Javascrpt。

var score=0;
function check (name) {
    var methods = document.getElementsByName('name');
    for (var i=0; i<methods.length; i++) {
         if (methods[i].checked == true) {
             score +=1;
             alert(score);
            }
   }
}

1 个答案:

答案 0 :(得分:0)

在您的HTML中,您尝试在a1事件中放置的"a1"函数中传递变量check()而不是字符串onclick,因此您应该替换:< / p>

onclick="check(a1)"

使用:

onclick="check('a1')"

在您的javascript中,您始终在寻找name="name"的元素,因此您应该替换:

var methods = document.getElementsByName('name');

使用:

var methods = document.getElementsByName(name);