JavaScript - 测验单选按钮和表单验证

时间:2015-02-08 09:54:29

标签: javascript html

当我点击按钮时,如何让我的按钮等级?它应该提供一个警告框,显示每个正确答案的所有分数。请参阅以下代码:

 !DOCTYPE html>
    <html>
        <head>
            <script src = "quiz.js"> </script>
        </head>
        <body>
            <form>
                <fieldset>
                    <legend> Question 1 </legend>
                    He _____ it. <br>
                    <input type = "radio" value = "wrong" name = "q1" id = "q"> don't like <br>
                    <input type = "radio" value = "right" name = "q1" id = "q"> doesn't like <br>
                    <input type = "radio" value = "wrong" name = "q1" id = "q"> don't likes <br>
                </fieldset> <br>

                <fieldset>
                    <legend> Question 2 </legend>
                    They _____ here very often. <br>
                    <input type = "radio" value = "right" name = "q2" id = "q"> don't come <br>
                    <input type = "radio" value = "wrong" name = "q2" id = "q"> doesn't comes <br>
                    <input type = "radio" value = "wrong" name = "q2" id = "q"> don't doesn't come <br>
                </fieldset> <br>

                <fieldset>
                    <legend> Question 3 </legend>
                    John and Mary _____ twice last week. <br>
                    <input type = "radio" value = "wrong" name = "q3" id = "q"> comes <br>
                    <input type = "radio" value = "wrong" name = "q3" id = "q"> come <br>
                    <input type = "radio" value = "right" name = "q3" id = "q"> coming <br>
                </fieldset> <br>

    function validate(){
        var cor = 0;
    var radios = document.getElementById('q');
      for(var i = 1; i < radios.length; i++){
          if (radios[i].checked == true && radios[i].value == "right") {
            cor++
          }
      }
    }alert("Correct " + cor);

1 个答案:

答案 0 :(得分:0)

将此添加到您的HTML

<button id="results" onclick="display()">
Show me the answers!
</button>

的Javascript

var cor=0;
function validate(){

    var radios = document.getElementById('q');
      for(var i = 1; i < radios.length; i++){
          if (radios[i].checked == true && radios[i].value == "right") {
            cor++
          }
      }
}
function display(){
    alert(cor);}