New to Javascript and HTML. In a nutshell, attempting to update score if user enters correct sum of random math problem. Not able to pass the answer of the problem to my function which checks if what the user entered is correct. I just want the score to increase by one. For some reason the function I am passing the parameter "score" to is not being recognized by it.
Here is a very quick example of my code. More concerned about the logic instead of the looks right now of the program. I know right now the score will not update correctly but the problem lies in the passing of the "answer" variable. I will easily work through the score increase once the function at least gets called. Thank you very much for your time!
<html>
<title></title>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload = "displayProblem()">
<script>
function displayProblem(){
var answer = (firstNum) + (secondNum);
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer === answer){
updateScore();
console.log("score updated");
}
console.log("did not update score");
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
var score = 0;
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns">
</div>
</div>
<input type="text" id="answr">
Score: <label id="score"> 0 </label>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
the prob is that every time you call the function "updateScore"
you reset the value of "score" to zero.
one way could be this: read the current score first than increase...
function updateScore(){
var score = pareseInt(document.getElementById("score").innerHTML);
score++;
document.getElementById("score").innerHTML = score;
}
or this: set score to "global" than increase...
var score = 0;
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
Try this:
<html>
<title></title>
<head>
</head>
<body onload="displayProblem()">
<script>
var answer;
var score=0;
function displayProblem(){
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer == answer)
updateScore();
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns"></div>
</div>
<input type="text" id="answr">Score: <label id="score"> 0 </label></input>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
You had 2 problems; one that answer was a local variable to displayProblem() and therefore wasn't accessible by checkAnswer(), and two that you were using === instead of ==. === evaluates both type and value, userAnswer and answer are of different types so this was evaluating to false.
JS fiddle
EDIT: score will increment as expected.
<html>
<title></title>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body onload = 'displayProblem()'>
<script>
//'answer','score' variables should be declared outside function globally
var answer=0;
var score=0;
function displayProblem(){
//var answer = (firstNum) + (secondNum); The calculation should be after assigning value to 'firstNum', 'secondNum'
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById('qstns').innerHTML = firstNum +' + ' + secondNum +' = ';
}
function checkAnswer(){
var userAnswer = document.getElementById('answr').value;
if(userAnswer == answer){
updateScore();
console.log('score updated');
}
else
console.log('did not update score');
}
function displayNext(){
document.getElementById('next').style.display = 'block';
}
function hideNext(){
document.getElementById('next').style.display = 'none';
}
function updateScore(){
score++;
document.getElementById('score').innerHTML = score;
}
function clearAnswer(){
document.getElementById('answr').value = ' ';
}
</script>
<div id='main'>
<div id='qstns'>
</div>
</div>
<input type='text' id='answr'>
Score: <label id='score'> 0 </label>
<button type='Sumbit' id='submit' onclick='displayNext(), checkAnswer();'>Check</button>
<button type='Submit' id='next' onclick='displayProblem(), hideNext(), clearAnswer();' style='display:none;'>Next</button>
</body>
</html>
Related
JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.
You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.
If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();
I have this JS / HTML code. It is supposed to give you an input. When you click the button as many times as you wrote in the input then it the screen is supposed to say 'stop' but that's not happening and idk why. How can I fix this?
var text2
let count = 1;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count = count + 1;
if (count === text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'>ok</button>
<div id='div'></div>
Refactor your code like this:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='div'>ok</button>
<div id='div'> </div>
<script>
var count = 0;
function check() {
let user_input = document.getElementById('questions').value;
if (++count === parseInt(user_input)) {
document.getElementById('div').innerHTML = "stop";
}
}
</script>
</body>
</html>
This shoud do the trick:
<html>
<body>
<p>how many?<input type="text" onInput="onInput()" id="questions"></p>
<button onclick="check()" id = 'but'> ok </button>
<div id = 'div'> </div>
<script>
var text2;
let count = 0
function onInput() {
var element = document.getElementById('questions');
//replace window
text2 = element.value;
}
function check(){
count = count + 1;
console.log(count);
if (count === parseInt(text2)){
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
You are using === to compare, which checks type before comparing. count is an integer and text2 is a String, so it will always return false. Instead, first parse text2 into an integer, then compare like so:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 0;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count === parseInt(text2)) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
Or instead use == which only checks for value:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count == text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.
My goal is to keep track of the attempts made in the game. This is my code so far.
I have edited this post to understand difference between count = 0 and count = 1.
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.getElementById("attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let count = 1
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value;
if (guessValue < randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too low";
count++
} else if (guessValue > randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too high";
count++
} else {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "You guessed correctly in " + count++ + "
attempts";
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Guess the number</title>
</head>
<body>
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
<script src="script.js"></script>
</body>
I can't understand why attempt.innerHTML won't work. It doesn't show up on the page like "result" does.
You are declaring a global attempt variable outside the function which holds the html element and then you are declaring a local attempt variable in your function which will always be 1.
Declare a counter outside the function and then increment it everytime your function is called.
Also in your answer you are only incrementing the count and updating the attempt.innerHTML inside your if else block under specific conditions. You want to move this code outside of the if else block so it updates on every guess.
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let attempt = document.querySelector(".attempt")
let attemptCounter = 0
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value
// Increment Attempts by 1
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
}
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
This is a simplified function version of setting up multiple number guessing games on a single page. All game related data is kept in dataset attributes num and try of the associated input field.
function guess(id){
let el = document.getElementById(id);
el.dataset.try=0;
el.dataset.num = Math.floor(Math.random() * 30) + 1;
el.onchange=()=>el.nextElementSibling.innerHTML =
"Attempt "+(++el.dataset.try)+":<br>Your guess is "
+["too low.","correct!","too high."]
[Math.sign(el.value-el.dataset.num)+1]
}
guess('guess1');guess('guess2');
<h1>GUESS SOME NUMBERS:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess1">
<div></div>
<p>Enter another guess:</p>
<input type="number" id="guess2">
<div></div>
You're redefining the attempt variable in a local scope as an integer which is overriding the reference to the document element. When you use "innerHTML" your using it on the localized attempt (an integer not the document element)
Try this:
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.querySelector(".attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
button.addEventListener("click", checkGuess)
let attemptCount = 1 // Renamed this from attempt and moved to global scope
function checkGuess() {
let guessValue = document.getElementById("guess").value
attempt.innerHTML = "Attempt n: " + attemptCount
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
attemptCount++;
}
I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }