On clicking submit I want the score and the correct answers to be printed on a new page. Right now the score pops up on an alert box. How can this be done in HTML/JavaScript ?
The code for my quiz application is :
<html>
<head>
<title>Quizzer</title>
<style type="text/css">
body {
background:#E3E1DC;
font-size:16px;
font-family:Helvetica, Arial;
line-height:1.2em;
color:#222222;
}
pre {
font-family:Consolas, Courier;
font-size: 12px;
color:#444444;
line-height:12px;
margin-left:30px;
margin-top:-28px;
}
.instructions {
margin-left:25px;
}
.button {
margin-left:10px;
margin-bottom:120px;
width:200px;
height:50px;
}
.question {
background:#F1E6D4;
padding:15px;
margin:10px;
}
.odd {
background:#9F9694;
}
.wrong {
border-left:#BA3D49 5px solid;
padding-left:10px;
}
</style>
<script langauge="JavaScript">
// number of questions in the quiz, this must be set exactly
var totalQuestions = 5;
// arrays to store answers, and user submited answers.
var answers = new Array;
var userAnswers = new Array;
// quiz answers
answers[1] = "B";
answers[2] = "C";
answers[3] = "D";
answers[4] = "D";
answers[5] = "B";
// sets the users answer selection to the appropriate array element
// in the userAnswers array.
// questionNumber is the question div id as well as the userAnswers
// array element index to store the answer in.
// answerSelection is the value of the selected answer from a question
function SetAnswer(questionNumber, answerSelection) {
userAnswers[questionNumber] = answerSelection;
}
// applies the .wrong class styling to any question div that is incorrect
function MarkIncorrectQuestions() {
for(i = 1; i <= totalQuestions; i++) {
if(answers[i] != userAnswers[i]) {
document.getElementById(i).className += " wrong";
}
}
}
// counts the number of correct answers
// returns the number of correct answers
function GetScore() {
var score = 0;
for(i = 1; i <= totalQuestions; i++) {
if(userAnswers[i] == answers[i])
score++;
}
return score;
}
// sets classes for each question div to its default styling.
function ApplyDefaultQuestionStyles() {
for(i = 1; i <= totalQuestions; i++) {
if(i % 2 == 0) {
document.getElementById(i).className = "question";
}
else {
document.getElementById(i).className = "question odd";
}
}
}
// calls all appropriate functions in order to check answers and mark
// incorrect questions.
function CheckQuiz() {
ApplyDefaultQuestionStyles();
var totalQuestions = '5';
var score = GetScore();
MarkIncorrectQuestions();
alert("You scored: " + score + " out of " + totalQuestions + ".");
//document.write("<h1>hello</h1>");
}
function result(score,totalQuestions){
document.write("Score" +score);
}
</script>
</head>
<body onLoad="ApplyDefaultQuestionStyles()">
<div class="instructions">
<h1>The Movie Quiz</h1>
</div>
<form>
<div id="1">
<p><strong>Question 1</strong></p>
<p>Where does “It’s a Wonderful Life” take place?</p>
<p><input type="radio" value="A" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Hills</p>
<p><input type="radio" value="B" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Falls</p>
<p><input type="radio" value="C" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Lake</p>
<p><input type="radio" value="D" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford City</p>
</div>
<div id="2">
<p><strong>Question 2</strong></p>
<p>In “The Godfather,” who was murdered in the causeway?</p>
<p><input type="radio" value="A" onClick="SetAnswer(2, this.value)" name="radiobutton2">Luca Brasi</p>
<p><input type="radio" value="B" onClick="SetAnswer(2, this.value)" name="radiobutton2">Moe Greene</p>
<p><input type="radio" value="C" onClick="SetAnswer(2, this.value)" name="radiobutton2">Sonny</p>
<p><input type="radio" value="D" onClick="SetAnswer(2, this.value)" name="radiobutton2">Paulie</p>
</div>
<div id="3">
<p><strong>Question 3</strong></p>
<p>Where did Princess Leia hide the stolen plans for the Death Star?</p>
<p><input type="radio" value="A" onClick="SetAnswer(3, this.value)" name="radiobutton2">In C-3PO</p>
<p><input type="radio" value="B" onClick="SetAnswer(3, this.value)" name="radiobutton2">In a pocket in the hem of her white gown</p>
<p><input type="radio" value="C" onClick="SetAnswer(3, this.value)" name="radiobutton2">In the Millennium Falcon</p>
<p><input type="radio" value="D" onClick="SetAnswer(3, this.value)" name="radiobutton2">In R2-D2</p>
</div>
<div id="4">
<p><strong>Question 4</strong></p>
<p>In which of the following films did Robert Duvall NOT appear?</p>
<p><input type="radio" value="A" onClick="SetAnswer(4, this.value)" name="radiobutton2">To Kill a Mockingbird</p>
<p><input type="radio" value="B" onClick="SetAnswer(4, this.value)" name="radiobutton2">The Godfather</p>
<p><input type="radio" value="C" onClick="SetAnswer(4, this.value)" name="radiobutton2">Tender Mercies</p>
<p><input type="radio" value="D" onClick="SetAnswer(4, this.value)" name="radiobutton2">One Flew Over the Cuckoo’s Nest</p>
</div>
<div id="5">
<p><strong>Question 5</strong></p>
<p>Who was Scarlett O’Hara’s second husband?</p>
<p><input type="radio" value="A" onClick="SetAnswer(5, this.value)" name="radiobutton2">Frank Kennedy</p>
<p><input type="radio" value="B" onClick="SetAnswer(5, this.value)" name="radiobutton2">Rhett Butler</p>
<p><input type="radio" value="C" onClick="SetAnswer(5, this.value)" name="radiobutton2">Ashley Wilkes</p>
<p><input type="radio" value="D" onClick="SetAnswer(5, this.value)" name="radiobutton2">Charles Hamilton</p>
</div>
<p>
<input type="submit" class="ui-button" onClick="CheckQuiz()" value="Submit Answers" name="submitButton" class="button"></p>
</form>
</body>
You have two options instead of using an alert ...
1) Create a layered popup that pops up in front of all your page content (you could darken the BG as well like most modals do). This would allow you to pop the message up in the same page and not require the user to open another window.
2) Your other option would be to popup a new window and use javascript to write the information to that window. See the following link for more information on this: http://www.electrictoolbox.com/write-content-dynamic-javascript-popup/
I personally would go with the first because it guarantees that it will work even if the user has a popup blocker.
Related
I have created a survey and get the result by using below code.I also want to send that code to particular mail and also print the result in PDF.below is the code.and also if there any suggestion how to get the result in new page and from where i can have button like send to email/send to pdf.
<p>
Select a radio button and click on Submit.
</p>
question 1:
<input type="radio" name="question1" value="1">1
<input type="radio" name="question1" value="2">2
<input type="radio" name="question1" value="3">3
<br>
question 2:
<input type="radio" name="question2" value="1">1
<input type="radio" name="question2" value="2">2
<input type="radio" name="question2" value="3">3
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
function displayRadioValue() {
document.getElementById("result").innerHTML = "";
var ele = document.getElementsByTagName('input');
for(i = 0; i < ele.length; i++) {
if(ele[i].type="radio") {
if(ele[i].checked)
document.getElementById("result").innerHTML
+= ele[i].name + " Value: "
+ ele[i].value + "<br>";
}
}
}
For print: Use window.print() with corresponding #media print in css
For email:
If you need the survey results to be emailed from site. you need to send the results from browser to server and make the server send email
If you need the survey response to be copied to user email client (say outlook) and you need them to send it to your email id, check below code.
<html>
<head>
<style>
#media print {
body * {
visibility: hidden;
}
#result, #result * {
visibility: visible;
}
#result {
position: absolute;
left: 0;
top: 0;
}
}
</style>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
<div>
question 1:
<input type="radio" name="question1" value="1">1
<input type="radio" name="question1" value="2">2
<input type="radio" name="question1" value="3">3
<br>
question 2:
<input type="radio" name="question2" value="1">1
<input type="radio" name="question2" value="2">2
<input type="radio" name="question2" value="3">3
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
</div>
<div id="result"></div>
<div id="control" style="display: none"><a id="toemail" href="mailto:youremail#domain.com?subject=Survey response&body=">Send to email</a> <button onclick="window.print();">Send to PDF</button></div>
<script>
function displayRadioValue() {
document.getElementById("result").innerHTML = "";
var ele = document.getElementsByTagName('input');
for(i = 0; i < ele.length; i++) {
if(ele[i].type="radio") {
if(ele[i].checked)
document.getElementById("result").innerHTML
+= ele[i].name + " Value: "
+ ele[i].value + "<br>";
}
}
document.getElementById("control").style.display = "block";
document.getElementById("toemail").href += document.getElementById("result").innerText;
}
</script>
</body>
</html>
Below is the code of a sample radio button quiz where multiple radio buttons are provided. Correct answers and wrong answers are defined in the code. User may check any answer or keep all blank. If user checks any radio button and finally clicks "Grade Me" button, label text of radio button of any wrong answers checked by the user shall appear as red and at the same time correct answer of that particular question shall appear in green (This will help the user know which question he answered wrong and what is its correct answer). I have tried several steps and searched many forums and failed. I think it will be really simple.
Example:
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
answers[0] = "doesn't like";
answers[1] = "don't come";
answers[2] = "come";
var wrong = new Array(3);
wrong[0] = "don't like";
wrong[1] = "doesn't come";
wrong[2] = "comes";
var wrong1 = new Array(3);
wrong1[0] = "doesn't likes";
wrong1[1] = "doesn't comes";
wrong1[2] = "coming";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < numQues; i++) {
currElt = i * numChoi;
answered = false;
for (j = 0; j < numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
answered = true;
if (currSelection.value == answers[i]) {
score += 3;
break;
}
if (currSelection.value == wrong[i]) {
score -= 1;
break;
}
if (currSelection.value == wrong1[i]) {
score -= 1;
break;
}
}
}
}
var scoreper = Math.round(score * 100 / 9);
form.percentage.value = scoreper + "%";
form.mark.value = score;
}
<title>Quiz Questions And Answers</title>
<center>
<h1>Quiz Questions</h1>
</center>
<p>
<form name="quiz">
<p>
<b><br>1. He -------------------- it.<br></b>
<label><input type="radio" name="q1" value="don't like">don't like</label><br>
<label><input type="radio" name="q1" value="doesn't like">doesn't like</label><br>
<label><input type="radio" name="q1" value="doesn't likes">doesn't likes</label><br>
<p><b>
<hr>
<br>2. They -------------------- here very often.<br></b>
<label><input type="radio" name="q2" value="don't come">don't come</label><br>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label><br>
<p><b>
<hr>
<br>3. John and Mary -------------------- twice a week.<br></b>
<label><input type="radio" name="q3" value="come">come</label><br>
<label><input type="radio" name="q3" value="comes">comes</label><br>
<label><input type="radio" name="q3" value="coming">coming</label>
<br>
<p><b>
<hr>
<p><b>
<input type="button"value="Grade Me"onClick="getScore(this.form);">
<input type="reset" value="Clear"><p>
Number of score out of 15 = <input type= text size 15 name= "mark">
Score in percentage = <input type=text size=15 name="percentage"><br>
</form>
<p>
<form method="post" name="Form" onsubmit="" action="">
</form>
Here is a rewrite of your code.
I fixed the illegal HTML and used best practices with event listeners, querySelectors and CSS
Please study the code and see if you understand. I can add more comments if needed
var answers = ["doesn't like","don't come","come"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
if (checked) score +=3;
}
else if (checked) {
score--;
rad.closest("label").classList.toggle("error")
}
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
.correct {
color: green
}
.error {
color: red
}
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/>
Number of score out of 15 = <input type="text" size="15" id="mark">
Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
In your getScore function, when you find out that a certain element has a correct answer selected (whichever var is the label - unless you are using a custom radio button which I would recommend since changing the background of the label element would simply highlight the words), you can give it a new class using JS.
currSelection.classList.add("correct");
or
currSelection.classList.add("incorrect");
Then in your CSS file you can have rules saying
.correct { background: green !important; }
.incorrect { background: red !important; }
WoW!....Close....Thanks for support. But still all the wrong answers are showing red color. This will let the user know which question he answered wrong. That part is Okay. But once the wrong answers are marked with red(I mean only the wrongly selected radio button choice texts and not the entire question and answer choices
the correct answer of that wrong attempt to be shown in green to enlighten the user. And the sad part is that I again failed with the CSS thing. I wanted to create a quiz in blog and added custom CSS with conditional tag in html of blogger post.....Not Working. However, I will add the modified code here so that you get a clear picture if I am doing rightly as you said.(How and where to add the CSS rules inside this code(if that is what you mean))
var answers = ["doesn't like", "don't come", "come"];
var rads, quiz; // need to be set after load
window.addEventListener("load", function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click", function(e) { // on submit
var score = 0;
var checked = quiz.querySelectorAll("input[type=radio]:checked"); // all checked radios
for (var i = 0; i < checked.length; i++) { // loop over all checked radios in the form
var idx = checked[i].name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var correct = checked[i].value == answers[idx];
checked[i].closest("p").classList.toggle("error", !correct)
checked[i].closest("p").classList.toggle("correct", correct)
score += correct ? 3 : -1; // this is called a ternary
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
<!DOCTYPE HTML>
<html>
<body>
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't https://stackoverflow.com/questions/53818896/change-label-text-of-all-radio-button-in-quiz-as-red-and-green/59801712#like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/> Number of score out of 15 = <input type="text" size="15" id="mark"> Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
</body>
</html>
You can try this:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var coffee = document.forms[0];
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
document.getElementById("score"+i).style.color = "green";
document.getElementById("order").value = "You Clicked Option " + i;
}
} }
</script>
</head>
<body>
<div id="score1" style="font-size: 50px">1</div>
<div id="score2" style="font-size: 50px">2</div>
<div id="score3" style="font-size: 50px">3</div>
<div id="score4" style="font-size: 50px">4</div>
**<form action="/action_page.php">
<input type="text" id="order" size="50">
<br>
<input type="radio" name="coffee" value="1" onclick="myFunction()">Option 1<br>
<input type="radio" name="coffee" value="2" onclick="myFunction()">Option 2<br>
<input type="radio" name="coffee" value="3" onclick="myFunction()">Option 3<br>
<input type="radio" name="coffee" value="4" onclick="myFunction()">Option 4<br>
</form>**
</body>
</html>
I'm having an issue where it's printing 2 of the same image on to the page. Can someone help me fix it? I've spent the past 2 hours working on it and it's due today. I have it so it prints to another page the results based on what choices you make.
<html>
<head>
<title>Spirit Animal Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="quiz.css">
<h1><div class="title">Spirit Animal Quiz</div></h1>
</head>
<body onLoad="start()">
<form>
<br> <br>
<div class= "questionsStyle">
<div class="question">1. How would you describe your skin?</div><br>
<div class="answer">
<input type="radio" name="q1" onClick="scorer(1,2)">Rough<br>
<input type="radio" name="q1" onClick="scorer(1,4)">Smooth<br>
<input type="radio" name="q1" onClick="scorer(1,3)">Both<br>
</div><br>
<div class="question">2. Which of these words best describes you?</div><br>
<div class="answer">
<input type="radio" name="q2" onClick="scorer(2,2)" >Introvert<br>
<input type="radio" name="q2" onClick="scorer(2,6)">Extrovert<br>
<input type="radio" name="q2" onClick="scorer(2,4)">In between<br>
</div><br>
<div class="question3">3. What's your favorite color?</div><br>
<div class="answer3">
<input type="radio" name="q3">Red<br>
<input type="radio" name="q3">Blue<br>
<input type="radio" name="q3">Green<br>
<input type="radio" name="q3">Yellow<br>
<input type="radio" name="q3">Pink<br>
<input type="radio" name="q3">Purple<br>
<input type="radio" name="q3">Orange<br>
<input type="radio" name="q3">Brown<br>
</div><br>
<div class="question">4. Which of the following best describes you?</div><br>
<div class="answer">
<input type="radio" name="q4" onClick="scorer(4,6)">Timid<br>
<input type="radio" name="q4" onClick="scorer(4,4)">Courageous<br>
<input type="radio" name="q4" onClick="scorer(4,2)">Tough<br>
<input type="radio" name="q4" onClick="scorer(4,8)">Cowardly<br>
</div><br>
<div class="question">5. Which of these do you prefer?</div><br>
<div class="answer">
<input type="radio" name="q5" onClick="scorer(5,4)">Peace and quiet<br>
<input type="radio" name="q5" onClick="scorer(5,6)">Noise and crowds<br>
</div><br>
<div class="question">6. Do you cook your own food?</div><br>
<div class="answer">
<input type="radio" name="q6" onClick="scorer(6,2)">Yes<br>
<input type="radio" name="q6" onClick="scorer(6,4)">No<br>
</div><br>
<div class="question"><br>7. Which would you describe yourself as</div><br>
<div class="answer">
<input type="radio" name="q7" onClick="scorer(7,6)">Patient<br>
<input type="radio" name="q7" onClick="scorer(7,8)">Impatient<br>
</div><br>
<input type="button" name="result" value="Find out your spirit animal." onClick="total()">
</div>
</form>
<script language="javascript">
//sets up an array for the answers that are given
var result = new Array(7);
function start() {
for(var i=0; i<7; i++) { result[i]=0; }
}
// Adds points together.
function total() {
score=0;
for (var i=0; i<7; i++) { score=score+result[i]; }
analyzer(score);
}
output = new Array();
output[0] = "You have a more tender personality and tend to like being around others or at least feel like there is someone around. Your spirit animal is the crowd-loving rabbit";
output[1] = "Your a bit skittish, but you tend to stick around unless something bothers you. You prefer groups, but occasionally tend to wander on your own. Your spirit animal is the timid and fun loving deer.";
output[2] = "You are capable of doing things on your own, but don't really have an issue when in a group. You can be a bit tough to work with at times, but you always do your part. Your spirit animal is the fierce and courageous wolf.";
output[3] = "You prefer being alone in peace and quiet. You are patient and willing to do your own work to get what you need. Your spirit animal is the tough and vicious alligator.";
output[4] = "I think you missed something"
output[5] = "Come on now, you didn't answer any questions."
img = new Array();
img[0] = new Image();
img[0].src = 'images/Rabbit.jpg';
img[1] = new Image();
img[1].src = 'images/Deer.jpg';
img[2] = new Image();
img[2].src = 'images/Wolf.jpg';
img[3] = new Image();
img[3].src = 'images/Alligator.jpg';
function analyzer (score) {
// use total to determine spirit animal
if (score > 35) { finish = 0;}
else { if (score > 30) { finish = 1;}
else { if(score > 24) { finish = 2;}
else { if(score > 15) { finish = 3;}
else { if(score > 1) { finish = 4; }
else { finish = 5; console.warn("Please answer the questions.");}
}
}
}
}
//Add the points into an array
display(output[finish])
display(img[finish])
}
function scorer(q, points) {
q=q-1;
result[q]=points
}
//ALERT RESULTS: Replace with page change if time feasible
function display(output) {
if (score > 35) {document.write(output); document.write('<img src="images/Rabbit.jpg">')}
else if (score > 30) {document.write(output); document.write('<img src="images/Deer.jpg">')}
else if(score > 24) {document.write(output); document.write('<img src="images/Wolf.jpg">')}
else if(score > 15) {document.write(output); document.write('<img src="images/Alligator.jpg">')}
}
CSS
h1 {font-size: 3em; margin: center; font-weight:5; background-color:
red;text-align: center; border-radius: 6px;}
body { background-color: white; padding: 10px;
font-family: 'Roboto', sans-serif; font-size: 20px;
position: relative
overflow: hidden;
color:white;
background: black;
padding: 20px;
}
#questionStyle .answer{
font-family: cursive;
}
Remove this
img = new Array();
img[0] = new Image();
img[0].src = 'images/Rabbit.jpg';
img[1] = new Image();
img[1].src = 'images/Deer.jpg';
img[2] = new Image();
img[2].src = 'images/Wolf.jpg';
img[3] = new Image();
img[3].src = 'images/Alligator.jpg';
I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...
I have created an HTML multiple choice question. I am facing a problem how to validate it. Below is the HTML code:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
When the user clicks the submit button, there should be an alert that will show a message based on what was selected.
If no option was selected, the alert box should say "please select choice answer".
If the "Scripting" option was selected, the alert box should say "Answer is correct !"
If an option different from "Scripting" is selected, the alert box should say "Answer is wrong".
I want to create this validation in JavaScript.
You have to use onclick attribute and more js
attach event hander to your button
get radio elements value
compare
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
Some changes
I made some changes to the code above to make it more 'abstract'
<h1>JavaScript is ______ Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer(d1.choice.value, 'Scripting')">Submit Answer</button>
<script>
var submitAnswer = function(valore, rightanswer) {
if (valore == rightanswer) {
alert("OK");
}
};
</script>
Another, more complex example
<div style="background-color:lightblue">
<h1>JavaScript is a <span id='a1'>______</span> Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Scripting', 'd1','a1')">
</form>
</div>
<div style="background-color:lightblue">
<h1>Python is a <span id='a2'>______</span> Language.</h1><br>
<form id="d2">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Wonderful"> Wonderful
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Wonderful', 'd2', 'a2')">
</form>
</div>
<script>
var validate = function(valore, rightanswer, form, span) {
var formname = document.getElementById(form)
var spanname = document.getElementById(span)
spanname.innerHTML = rightanswer;
if (valore == rightanswer) {
formname.innerHTML ="<div style='background-color:lightgreen'><h1>GREAT! YOU'RE RIGHT: The answer, in fact, was: " + rightanswer + "</h1></div>";
}
else {
formname.innerHTML ="<div style='background-color:pink'><h1>Sorry, you where wrong: The answer was: " + rightanswer + "</h1></div>";
}
};
</script>
Use the required keyword. This prompts the user to choose a value, when the submit button is pressed without choosing any option. And always prefer to use
<input type="submit" value="submit"> over <button>Submit Answer</button>
while handling forms. Use the onclick() event handler to call your Javascript code.
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting" required> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<input type="submit" value="submit" onclick="validate()">
</form>
And the javascript part is as follows.
<script type="text/javascript">
function validate() {
var a= document.getElementByName("choice");
for (var i = 0, i < a.length; i++) {
if (a[i].checked) {
if( a[i].value == "scripting" )
alert("your answer is correct");
else
alert("your answer is not correct");
break;
} } }
</script>
Here condition is showing in alert pop up box. but I want to show it in a html tag.
But after clicking submit button, innerHTML content showing a millisecond and then automatic remove the content. How selection will stay in innerHTML
document.getElementById("answer").innerHTML;
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
document.getElementById("answer").innerHTML = "please select choice answer";
} else if ( val == "Scripting" ) {
document.getElementById("answer").innerHTML = "Answer is correct !"
} else {
document.getElementById("answer").innerHTML = "Answer is wrong"
}
};
You can add a function and event onClick so that whenever someone clicks on option submit button will appear.