简体   繁体   English

HTML / Javascript单选按钮测验

[英]HTML/Javascript Radio Button Quiz

I'm trying to validate the radio buttons so that an error pops up when it's not checked. 我正在尝试验证单选按钮,以便在未选中时弹出错误。

However the error won't disappear unless I select an option from the Question 2 set and nothing from Question 1. 但是,除非我从问题2集中选择一个选项而问题1中没有选项,否则错误不会消失。

I'm trying to have both messages pop up for both questions if unchecked and and individually disappear when something is selected for that question 我试图在未选中的情况下同时弹出这两个问题的消息,并在为该问题选择某些内容时单独消失

 //Javascript var answers = ["A","C"], total = answers.length; function getCheckedValue(radioName) { var radios = document.getElementsByName(radioName); var errorSpan = document.getElementById("choice_error"); var isChecked = false; errorSpan.innerHTML = ""; for (var y = 0; y < radios.length; y++) { if(radios[y].checked) { isChecked = true; return radios[y].value } else if(!radios[y].checked) { isChecked = false; errorSpan.innerHTML = "Please select a choice."; } } return isChecked; } function getScore() { var score = 0; for (var i = 0; i < total; i++) { document.getElementById("flag"+i).innerHTML = ""; if(getCheckedValue("choice"+i) == answers[i]) { score += 1; document.getElementById("flag"+i).innerHTML = "Your answer is correct."; } else if(getCheckedValue("choice"+i) != answers[i]) { document.getElementById("flag"+i).innerHTML = "Your answer is incorrect."; } } return score; } function returnScore() { var x = document.getElementById("myText").value; document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total; } 
 <!--HTML --> <!DOCTYPE html> <html lang="en"> <head> <title>Disney Quiz</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="images/favicon.ico"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="scripts/quiz.js"></script> </head> <body> <header><h1>Disney Quiz</h1></header> <main> <p>Click on the correct answer for each question and submit your results.</p> <form> <fieldset> <legend>Trivia Questions</legend> <label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last"value=""><br> <section id="radio1"> <p> Question 1) What was Walt Disney's first character he created? <span id="choice_error"></span></p> <input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit<br> <input type="radio" name="choice0" value="B">Donald Duck<br> <input type="radio" name="choice0" value="C">Mickey Mouse<br> <input type="radio" name="choice0" value="D">Goofy<br> <p id="flag0"></p> </section> <section id="radio2"> <p> Question 2) Snow White was the first ____ to ever be produced successfully. <span id="choice_error"></span></p></p> <input type="radio" name="choice1" value="A">Movie<br> <input type="radio" name="choice1" value="B">Live-Action<br> <input type="radio" name="choice1" value="C">Cel-animated Film<br> <input type="radio" name="choice1" value="D">Cartoon<br> <p id="flag1"><p> </section> <br> <input type="button" onclick="returnScore()" value="Show Results"> <input type="button" onclick="window.location.href = 'index.html';" value="Review"> <p id="results"></p> </fieldset> </form> </main> <aside> </aside> <footer> <p align="center"> Project 4 - Fall 2018 </p> </footer> </body> </html> 

In your code both error spans have the same ID "choice_error". 在您的代码中,两个错误跨度都具有相同的ID“choice_error”。 No two html elements should have the same id, as then the browser won't be able to differentiate them. 没有两个html元素应具有相同的ID,因为浏览器将无法区分它们。

If you want to access both error span elements, you can give each of them a ccs class "choice_error" and call the method document.getElementsByClassName(). 如果要访问两个错误范围元素,可以为每个元素提供一个ccs类“choice_error”,并调用方法document.getElementsByClassName()。

Also you need to clear the error span inside the loop 您还需要清除循环内的错误范围

 function getCheckedValue(radioName) { var radios = document.getElementsByName(radioName); var errorSpans = document.getElementsByClassName("choise_error"); var isChecked = false; for (var y = 0; y < radios.length; y++) { errorSpans[y].innerHTML= ""; // clear the span if(radios[y].checked) { isChecked = true; return radios[y].value } else if(!radios[y].checked) { isChecked = false; errorSpans[y].innerHTML = "Please select a choice."; // error message } } return isChecked; } 

fastest method: 最快的方法:

HTML : HTML

<span id="choice_error_choice0"></span>
<!-- ... -->
<span id="choice_error_choice1"></span>

JS : JS

function getCheckedValue(radioName)
{
    let isChecked = true;
    let exist = document.querySelector(`input[name='${radioName}']:checked`);
    let choice_error = document.getElementById('choice_error_'+radioName);

    choice_error.innerHTML = "";

    if (exist == null)
    {
        isChecked = false;
        choice_error.innerHTML = "Please select a choice.";
    }

    return isChecked;

}

I've tidied a couple of things up. 我已经整理了几件事。 Using label for a start. 使用label开始。

The main difference is I now use a parent question id to group our answers and change to class for choice_error . 主要区别在于我现在使用父问题id对我们的答案进行分组并更改为class for choice_error

Then I've use document.querySelector to find the checked answer and set the child error messages display style. 然后我使用document.querySelector来查找已检查的答案并设置子错误消息显示样式。

 //Javascript var answers = ["A", "C"], total = answers.length; function getAnswer(QuestionId) { //Get the selected answer radio button var answer = document.querySelector("#" + QuestionId + " input[type=radio]:checked"); //It there isn't one if (answer === null) { //show the error mesage document.querySelector("#" + QuestionId + " .choice_error").style.display = "inline"; } else { //Otherwise hide the message document.querySelector("#" + QuestionId + " .choice_error").style.display = ""; //And set the answer value answer = answer.value; } return answer; } function getScore() { var score = 0; for (var i = 0; i < total; i++) { document.getElementById("flag" + i).innerHTML = ""; if (getAnswer("radio" + (i + 1)) == answers[i]) { score += 1; document.getElementById("flag" + i).innerHTML = "Your answer is correct."; } /*No need to check again, it either matches or doesn't*/ else { document.getElementById("flag" + i).innerHTML = "Your answer is incorrect."; } } return score; } function returnScore() { var x = document.getElementById("myText").value; document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total; } 
 .questions label { display: block; } .choice_error { color: red; display: none; } 
 <!--HTML --> <!DOCTYPE html> <html lang="en"> <head> <title>Disney Quiz</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="images/favicon.ico"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="scripts/quiz.js"></script> </head> <body> <header> <h1>Disney Quiz</h1> </header> <main> <p>Click on the correct answer for each question and submit your results.</p> <form> <fieldset> <legend>Trivia Questions</legend> <label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br> <section id="radio1" class="questions"> <p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p> <label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label> <label><input type="radio" name="choice0" value="B">Donald Duck</label> <label><input type="radio" name="choice0" value="C">Mickey Mouse</label> <label><input type="radio" name="choice0" value="D">Goofy</label> <p id="flag0"></p> </section> <section id="radio2" class="questions"> <p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p> <label><input type="radio" name="choice1" value="A">Movie</label> <label><input type="radio" name="choice1" value="B">Live-Action</label> <label><input type="radio" name="choice1" value="C">Cel-animated Film</label> <label><input type="radio" name="choice1" value="D">Cartoon</label> <p id="flag1"> <p> </section> <br> <input type="button" onclick="returnScore()" value="Show Results"> <input type="button" onclick="window.location.href = 'index.html';" value="Review"> <p id="results"></p> </fieldset> </form> </main> <aside> </aside> <footer> <p align="center"> Project 4 - Fall 2018 </p> </footer> </body> </html> 

We could refactor this some more, let one method handle manipulating the question related actions. 我们可以再修改一下,让一个方法处理操作问题相关的操作。

 //Javascript var answers = ["A", "C"], total = answers.length; function checkAnswer(QuestionId, Answer) { var isCorrect = false; var questionElement = document.getElementById(QuestionId); //Get the selected answer radio button var answerElement = questionElement.querySelector("input[type=radio]:checked"); //It there isn't one if (answerElement === null) { //show the error mesage questionElement.querySelector(".choice_error").style.display = "inline"; questionElement.querySelector("[id^=flag]").innerHTML = ""; } else { //Otherwise hide the message questionElement.querySelector(".choice_error").style.display = ""; //And chcek answer isCorrect = Answer == answerElement.value; questionElement.querySelector("[id^=flag]").innerHTML = "Your answer is " + (isCorrect ? "correct" : "incorrect"); } return isCorrect; } function getScore() { var score = 0; for (var i = 0; i < total; i++) { if(checkAnswer("radio" + (i + 1), answers[i])) { score++;} } return score; } function returnScore() { var x = document.getElementById("myText").value; document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total; } 
 .questions label { display: block; } .choice_error { color: red; display: none; } 
 <!--HTML --> <!DOCTYPE html> <html lang="en"> <head> <title>Disney Quiz</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="images/favicon.ico"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="scripts/quiz.js"></script> </head> <body> <header> <h1>Disney Quiz</h1> </header> <main> <p>Click on the correct answer for each question and submit your results.</p> <form> <fieldset> <legend>Trivia Questions</legend> <label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br> <section id="radio1" class="questions"> <p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p> <label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label> <label><input type="radio" name="choice0" value="B">Donald Duck</label> <label><input type="radio" name="choice0" value="C">Mickey Mouse</label> <label><input type="radio" name="choice0" value="D">Goofy</label> <p id="flag0"></p> </section> <section id="radio2" class="questions"> <p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p> <label><input type="radio" name="choice1" value="A">Movie</label> <label><input type="radio" name="choice1" value="B">Live-Action</label> <label><input type="radio" name="choice1" value="C">Cel-animated Film</label> <label><input type="radio" name="choice1" value="D">Cartoon</label> <p id="flag1"> <p> </section> <br> <input type="button" onclick="returnScore()" value="Show Results"> <input type="button" onclick="window.location.href = 'index.html';" value="Review"> <p id="results"></p> </fieldset> </form> </main> <aside> </aside> <footer> <p align="center"> Project 4 - Fall 2018 </p> </footer> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM