I am making a quiz app and i was trying to increase the question number and score every time they go to the next question. Also would like to give some feed back when they get it the question right or wrong. Any tips will be greatly appreciated. New to coding and really trying to figure this all out
let currentQuestion = 0;
let score = 1;
function renderQuestion() {
document.getElementById("quiz").innerHTML =
`
<fieldset>
<legend> ${questions[currentQuestion].question} </legend>
<input type="radio" name="option"
value="A">${questions[currentQuestion].options[0].option}<br>
<input type="radio" name="option"
value="B">${questions[currentQuestion].options[1].option}<br>
<input type="radio" name="option"
value="C">${questions[currentQuestion].options[2].option}<br>
<input type="radio" name="option"
value="D">${questions[currentQuestion].options[3].option}<br>
<button id="button" class="submitAnswer"> Submit answer </button>
<div id="errorMessage">
</div>
<div id="feed">
</div>
</fieldset>
`;
document.getElementById("button").addEventListener("click",
function(event) {
event.preventDefault();
let hasAnswer = false;
for (let el of document.querySelectorAll("input")) {
if (el.checked) {
hasAnswer = true;
if (el.value === questions[currentQuestion].answer)
{
score++;
}
}
}
if (hasAnswer) {
if (currentQuestion === questions.length - 1) {
document.getElementById("quiz").innerHTML = `Your score is
${score}`;
}
else {
currentQuestion++;
renderQuestion();
}
}
else {
document.getElementById("errorMessage").innerHTML = "Please
select an answer!";
}
});
}
renderQuestion();
If you want to increase the score every time they move to the next question, the easiest way would be to add this:
score++;
Inside this:
else {
currentQuestion++;
score++;
renderQuestion();
}
Which is inside this block:
if (hasAnswer) {
if (currentQuestion === questions.length - 1) {
document.getElementById("quiz").innerHTML = `Your score is
${score}`;
}
else {
currentQuestion++;
score++;
renderQuestion();
}
}
else {
document.getElementById("errorMessage").innerHTML = "Please
select an answer!";
}
Hopefully this helps!
Related
I need to create a new function that will return the number of each win, lose, and tie results. With each of the user's selection (rock, paper, or scissors), and by clicking the "GO!" button it will update all the counters and logs.
The HTML displays a form of buttons (each for rock paper and scissors options), as well as the executing "GO!" button.
The JS only has one function play() and executes the randomizing of the rock, paper, scissors array which will determine what the computer will choose. This function only declares whether each match is a win, loss, or tie, but does not record it (thank you to user #BarMar for helping me with this part):
function play() {
var types = ['Rock', 'Paper', 'Scissors'];
var computer_choice = types[Math.floor(Math.random() * (types.length))];
document.getElementById("choiceDisplay").innerHTML = computer_choice;
var user_button = document.querySelector("input[name=choice]:checked");
if (user_button) {
var user_choice = user_button.value;
} else {
window.alert("You have to choose Rock, Paper, or Scissors first.");
return;
}
if (user_choice == computer_choice) {
document.getElementById("result").textContent = "Tie!";
return;
}
switch (computer_choice) {
case "Rock":
if (user_choice == "Paper") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
break;
case "Paper":
if (user_choice == "Scissors") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
break;
case "Scissors":
if (user_choice == "Rock") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
}
}
<html>
<body>
<div class="stuff">
<h2> Select one: </h2>
<div class="choices">
<p>
<form>
<input type="radio" name="choice" value= "Rock" id="Rock"/>Rock
<br>
<input type="radio" name="choice" value= "Paper" id="Paper"/>Paper
<br>
<input type="radio" name="choice" value="Scissors" id="Scissors"/>Scissors
</form>
</p>
</div>
<div class= "choiceDisplay">
<div class = "ccc">The Computer Chose:</div>
<p id= "choiceDisplay"></p>
<div class = "button"> <button onclick="play()">GO!</button> </div>
<div class= "label"><p id = "result"></p></div>
</div>
</div>
</body>
</html>
I'm guessing this is a homework problem because I've seen it twice now lol; Anyway one way to do this would be to add displays for the results and update them.
Display
<h4>Wins <span id="wins">0</span></h4>
<h4>Losses <span id="losses">0</span></h4>
<h4>Ties <span id="ties">0</span></h4>
Update structure
var wins = document.getElementById("wins");
wins.innerHTML = parseInt(wins.innerHTML) + 1;
Example
https://jsfiddle.net/8qpz9tnx/
Outside of the function, I have declared a global, empty array called "record".
var record = [];
Every time the user loses, wins or ties, I add the result to the array using the "push" method as follows:
record.push("Tie");
At the end of of the HTML file, I have added an empty div with the ID of records for easy retrieval.
<div id="records"></div>
At the end of the play() function, I have added a snippet to filter and display the results.
document.getElementById("records").innerHTML = "<p>You lost " + record.filter(x => x=="Lose").length + " times.</p><p>You won " + record.filter(x => x=="Win").length + " times.</p><p>It's been a tie " + record.filter(x => x=="Tie").length + " times.</p>";
In the code snippet above, you will notice this piece which counts the number of times the person won:
record.filter(x => x=="Win").length
var record = [];
function play() {
var types = ['Rock', 'Paper', 'Scissors'];
var computer_choice = types[Math.floor(Math.random() * (types.length))];
document.getElementById("choiceDisplay").innerHTML = computer_choice;
var user_button = document.querySelector("input[name=choice]:checked");
if (user_button) {
var user_choice = user_button.value;
} else {
window.alert("You have to choose Rock, Paper, or Scissors first.");
return;
}
if (user_choice == computer_choice) {
document.getElementById("result").textContent = "Tie!";
record.push("Tie");
} else {
switch (computer_choice) {
case "Rock":
if (user_choice == "Paper") {
document.getElementById("result").textContent = "You Win!";
record.push("Win");
} else {
document.getElementById("result").textContent = "You Lost.";
record.push("Lose");
}
break;
case "Paper":
if (user_choice == "Scissors") {
document.getElementById("result").textContent = "You Win!";
record.push("Win");
} else {
document.getElementById("result").textContent = "You Lost.";
record.push("Lose");
}
break;
case "Scissors":
if (user_choice == "Rock") {
document.getElementById("result").textContent = "You Win!";
record.push("Win");
} else {
document.getElementById("result").textContent = "You Lost.";
record.push("Lose");
}
}
}
document.getElementById("records").innerHTML = "<p>You lost " + record.filter(x => x=="Lose").length + " times.</p><p>You won " + record.filter(x => x=="Win").length + " times.</p><p>It's been a tie " + record.filter(x => x=="Tie").length + " times.</p>";
}
<html>
<body>
<div class="stuff">
<h2> Select one: </h2>
<div class="choices">
<p>
<form>
<input type="radio" name="choice" value= "Rock" id="Rock"/>Rock
<br>
<input type="radio" name="choice" value= "Paper" id="Paper"/>Paper
<br>
<input type="radio" name="choice" value="Scissors" id="Scissors"/>Scissors
</form>
</p>
</div>
<div class= "choiceDisplay">
<div class = "ccc">The Computer Chose:</div>
<p id= "choiceDisplay"></p>
<div class = "button"> <button onclick="play()">GO!</button> </div>
<div class= "label"><p id = "result"></p></div>
<div id="records"></div>
</div>
</div>
</body>
</html>
The issue with this is that the record array could easily be manipulated/hacked with dev tools.
I'm building up a quiz app in javascript only, I want to make the final step which calculates the final score. I have 2 var : myl & score : myl = DOM.checked of my input, score = 0.
I need to make it this way:
if(myl.checked == True) {
score += 1
}
Then I'd like to print the total score in the div, but every time I try to get the total score I get only = 1 and the value of score didn't increased. Can any one help me please
I tried to set score = 0 and myl = DOM.checked and put
if(dom.checked == true) { score += 1} then DOM.innerHTML = score
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var myscore = 0;
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
I always get 1 as result of score, not the total of correct or chosen inputs which should be 4
Because your myscore is declared inside myFunction() so it always start at 0 and plus 1 when a checkbox checked. Move it outside the function will solve it.
Or if you just want to get the amount of checked checkbox, document.querySelectorAll('input:checked').length may help.
Demo:
var myscore = 0;
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo1").innerHTML = document.querySelectorAll('input:checked').length;
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
<div id="demo1"></div>
You need to set (var myscore = 0) outside of the function
Refactor JS portion below the way you want or build on top of it
The for loop checks to see if the checkbox is true or false - with each time adding +1. That sum is added to a variable and pushed back to the DOM.
Codepen Demo: https://codepen.io/aystarz52/pen/JQVzKz?editors=1111
HTML
Check what applies to you: <br />
<label>Are you a boy?<input type="checkbox" id="myCheck"></label><br />
<label>Are you a girl?<input type="checkbox" id="myCheck1"></label><br />
<label>Are you a car?<input type="checkbox" id="myCheck2"></label><br />
<label>Are you a dog?<input type="checkbox" id="myCheck3"></label><br />
<hr />
<label><button class="checks" onclick="checks()">Check Checkbox</button></label>
<div id="answered"></div>
<label><button class="unchecked" onclick="uncheck()">Uncheck Checkbox</button></label>
<div id="missed"></div>
<label><button class="finalscore" onclick="myFunction()">Final Score</button></label>
<div id="demo"></div>
Style
.hide {
display: none;
}
Javascript
var myscore = 0;
var missed = 0;
var answered = 0;
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var array1 = [myl, myl1, myl2, myl3];
function myFunction() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = "You scored " + myscore + " Out Of 4";
document.querySelector(".finalscore").className += " hide";
}
}
function checks() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
answered += 1;
}
document.getElementById("answered").innerHTML = "You answered " + answered + " Out Of 4";
document.querySelector(".checks").className += " hide";
}
}
function uncheck() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == false) {
missed += 1;
}
document.getElementById("missed").innerHTML = "You missed " + missed + " Out Of 4";
document.querySelector(".unchecked").className += " hide";
}
}
I am trying to make a program that prompts the user to guess a number from 1 to 1000. The program generates a random number and then the user has to guess the number until they get it right. The program alerts the user if their guess is too low or too high. Upon entering the right number, they are congratulated and asked if they want to run it again. I have read my book and even looked online for guidance, but against my best effort all it does is display the text field with the calculate button...no window messages or anything. Please help as I am stumped. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
There is a } missing in line 45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
}
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
Jquery way if you mind
var a = Math.floor((Math.random() * 100) + 1);
$(document).ready(function(){
$('#numberrandom').text(a);
});
$('#calculate').bind('click',function(){
entrynumber=$('#entry').val();
if(entrynumber > a){
alert('Your number is higher than it')
}
else if(entrynumber < a){
alert('Your number is lower than it')
}
else if(entrynumber == a){
alert('nice you won')
location.reload();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
<span>generated number: </span><span id='numberrandom'></span>
</div>
</form>
</body>
I'm trying to make my first input field automatically display a random multiplication sum, the user should then answer that sum in the second input field. Then when the user would click the button "check my answer", and a pop-up window.alert would appear saying either "You did it" or "Wrong!" etc.
Plus, for some reason, when I delete that empty function, my multiplication sums stop working! Can anyone shed some light?
Here's my code:
var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
var Question = x + " times " + y;
document.getElementById("inputVal").value = Question;
return Question;
}
function genAnswer() {
answer = x * y;
return answer;
}
window.onload = genQuestion;
function buttonPressed() {
var userAnswer = document.getElementById("outputVal").value;
if (answer === userAnswer) {
alert("Correct- Well Done!");
}
else {
alert("Wrong- Please try again!");
}
}
function d() {
}
<h1>Learn to Multiply Website</h1>
<form name="myForm" id="myForm" action="#">
<label>What is</label>
<input id="inputVal" name="inputVal" type="text"/>
<br>
<label>The answer is</label>
<input name="outputVal" id="outputVal" type="text"/>
<br>
<button class="button" onclick="buttonPressed()">Check my Answer</button>
</form>
You are using answer which in not declared.
You can directly call you answer function to genAnswer to compare with question
changed === to == for automatic type conversion.
Updated code
var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
var Question = x + " times " + y;
document.getElementById("inputVal").value = Question;
return Question;
}
function genAnswer() {
answer= x * y;
return answer;
}
window.onload = genQuestion;
function buttonPressed(){
var userAnswer = document.getElementById("outputVal").value;
if (userAnswer == genAnswer()){
alert("Correct- Well Done!");
}
else {alert("Wrong- Please try again!");}
}
function d(){}
<h1>Learn to Multiply Website</h1>
<form name="myForm" id="myForm" action="#">
<label>What is</label>
<input id="inputVal" name="inputVal" type="text" />
<br>
<label>The answer is</label>
<input name="outputVal" id="outputVal" type="text" />
<br>
<button class = "button" onclick="buttonPressed()">Check my Answer</button>
</form>
Your if statement is invalid:
function buttonPressed() {
var userAnswer = document.getElementById("outputVal").value;
if (answer === userAnswer) {
alert("Correct- Well Done!");
}
Because "answer" is not a variable, it's a value returned by the function "genAnswer".
So your "if" statement should go like this:
If(genAnswer() == userAnswer){}
I am pretty new on Javascript coding. I'm creating a web page for surveys or testing by myself.
Now here is my code;
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q2"> false
</form>
<button onclick="myFunction()"> try </button>
function myFunction(){
var form = document.getElementById('q1form'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1= parseInt(s1[n].value);
}
}
if(soru1==1){
document.writeln("Your answer is correct!");
}
else{
document.wirteln("Your answer is not correct");
}
}
In this code I want to display "Your answer is correct!" or other answer near the 'try' button. I can display answer with window.alert but I want to do it near button, in same page. Is it possible? How can I do it?
You could use a div next to the button <span id="feedback"></span> and then insert the feedback into that div:
var feedback = document.getElementById("feedback");
feedback.innerHTML = "Your answer is correct!";
Something like
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1">true
<input type="radio" name="question1" value="0" id="q2">false
</form>
<button onclick="myFunction(this)">try</button>
<script>
function myFunction(btn) {
var form = document.getElementById('q1form'),
s1 = form['question1'],
p = document.createElement('p'),
txt,
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1 = parseInt(s1[n].value);
}
}
if (soru1 == 1) {
txt = "Your answer is correct!"
} else {
txt = "Your answer is not correct";
}
var oldP = document.getElementById('response');
if (oldP) oldP.parentNode.removeChild(oldP);
p.appendChild(document.createTextNode(txt));
p.id = "response";
btn.parentNode.insertBefore(p, btn.nextSibling);
}
</script>
FIDDLE
This should get you started:
function myFunction() {
var form = document.getElementById('q1form'),
output = document.getElementById('output'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1 = parseInt(s1[n].value);
}
}
output.innerHTML = soru1 === 1 ? "Your answer is correct!"
: "Your answer is not correct" ;
}
Working fiddle here.
You can use:
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q2"> false
</form>
<button onclick="myFunction()"> try </button>
<span id="demo"></span>
function myFunction(){
var form = document.getElementById('q1form'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1= parseInt(s1[n].value);
}
}
if(soru1==1){
document.getElementById("demo").innerHTML="Your answer is correct";
}
else{
document.getElementById("demo").innerHTML="Your answer is not correct";
}
}