Can't change text in 'on click' javascript - javascript

I am doing a 'if,else' statement in javaScript. I want to change the "h2" text. I think I'm missing some code
<div id="game">
<p id="howMany">How many fingers am I holding up?</p>
<p id="theGame"> <input type="guess" id="guess" placeholder="0 to 5">
<button id="check-guess"> Guess! </button>
</p>
<div id="theAnswer">
<h2 id="h2">Your Reward</h2>
</div>
</div>
document.getElementById("check-guess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
document.getElementsById("h2").innerHTML = "You got it!";
} else {
document.getElementsById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber ;
}
}

Your function getElementsById doesn't exist, it could be getElementById. The value you pass needs to be an id, not a tagname.
document.getElementById("check-guess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
document.getElementById("h2").innerHTML = "You got it!";
} else {
document.getElementById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber;
}
}
<input id="guess">
<button id="check-guess">Check</button>
<h2 id="h2">Test</h2>

Related

Random math game in JavaScript

I'm trying to make a math game in JS like this:
Easy level: This level contains 5 questions contains three digits for example 1 + 2;
2 marks are calculated for each question. If the student gets a 7, he is congratulated by a moving animation and music of success, and if he does not get a passing mark, the sound of loss is heard.
and I want to show what's the score he got from correct answers.
like this sample output:
you lose and got 0/5, something like that.
I already do that and I did not get the output as I want, I think I have errors in the if statement.
This is my HTML code
<section>
<h1>Math Addition Quiz Game</h1>
<div class="centerdiv">
<div class="insertBox">
<div class="box1">
<p id="v1"> </p>
<p class="text-center justify-content-center" id="final"></p>
<p class="text-center justify-content-center" id="final1"></p>
</div>
<div class="box1">
<p id="operator">+</p>
</div>
<div class="box1">
<p type="text" id="v2"></p>
</div>
</div>
<div class="middleBox">
<input type="text" id="answ">
</div>
<div class="sentBox">
<button onclick="jsGame()" class="mb-3" id="submit"> Check Answer</button> <br>
<button onclick="Restart()" class="mb-3"id="restart" > Restart </button>
<button onclick="Main()" id="Main"> Back To Main Menu</button>
</div>
</div>
</section>
This is Java Script Code
let n1 = Math.floor(Math.random()*10+1)
let n2 = Math.floor(Math.random() * 10 + 1)
document.getElementById('v1').innerHTML = n1;
document.getElementById('v2').innerHTML = n2;
var count = 0;
var wrong = 0;
var score = 0;
document.getElementById('v1').value = n1;
document.getElementById('v2').value = n2;
document.getElementById('restart').style.visibility = "hidden";
document.getElementById('Main').style.visibility = "hidden";
let ans = n1 + n2;
const jsGame = () => {
var usera = document.getElementById('answ').value;
if (usera == ans) {
audio.play();
wrong = 0; //wrong answers
score++;
count++; //correct answers
GenerateRandom();
}
else {
//sad.play();
wrong = wrong+1;
document.getElementById('answ').value = " ";
alert(`Correct Answer is ${ans} Try Again. `);
}
if (score == 5) {
level.play();
Visible();
var s = 10 - wrong;
if (s >= 5) {
level.play();
document.getElementById("final").innerHTML = `you win and got ${s}/10`
document.getElementsById('submit').style.visibility = "hidden";
document.getElementById('operator').style.visibility = "hidden";
}else{
sad.play();
document.getElementById('answ').value = " ";
document.getElementById("final").innerHTML = `you lose and got ${wrong}/10`
}
}
};
function GenerateRandom() {
document.getElementById('answ').value = " ";
n1 = Math.floor(Math.random() * 10 + 1)
n2 = Math.floor(Math.random() * 10 + 1)
document.getElementById('v1').innerHTML = n1;
document.getElementById('v2').innerHTML = n2;
document.getElementById('v1').value = n1;
document.getElementById('v2').value = n2;
ans = n1 + n2;
}
function Restart() {
window. location. reload();
}
function Main() {
location.href="./game.html";
}
var audio = new Audio('../Congratulations-sound.mp3');
var sad = new Audio('../sad.wav');
var level = new Audio('../level.wav')
function Visible() {
document.getElementById('v1').style.visibility = "hidden";
document.getElementById('v2').style.visibility = "hidden";
document.getElementById('answ').style.visibility = "hidden";
document.getElementById('submit').style.visibility = "hidden";
document.getElementById('operator').style.visibility = "hidden";
document.getElementById('restart').style.visibility = "visible";
document.getElementById('Main').style.visibility = "visible";
}
I hope you can help me, and any modification or better addition to the code please help me. Thank you.
This is a Demo of what I did.
demo in github
repo in Github of all codes

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');

How to display diffrent images using if function after pressing a button

For my collage assignment i need to create a html webpage where if you press the button yes it displays a number and a corresponding image. i have figured out how to create the random number but cannot get the corresponding image to show up when the button in pressed. i am very new to this and any help would be appreciated
This is the java script
function randomNumber() {
var ranNumgen = Math.floor((Math.random() * 6) + 1);
}
console.log("randomNumber");
if ("number" == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if ("number" == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if ("number" == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if ("number" == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if ("number" == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if ("number" == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
And this is all my code
<!DOCTYPE html>
<html>
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
<script type="text/javascript">
function randomNumber() {
var ranNumgen = Math.floor((Math.random() *6) +1);
}
console.log("randomNumber");
if ("number" ==1 ) {
document.getElementById('img1').src ="image/dice1.jpg";
}
else if ("number" ==2) {
document.getElementById('img1').src ="image/dice2.jpg";
}
else if ("number"==3) {
document.getElementById("img1").src="image/dice3.jpg"
}
else if ("number"==4) {
document.getElementById("img1").src="image/dice4.jpg";
}
else if ("number"==5) {
document.getElementById("img1").src="image/dice5.jpg";
}
else if ("number"==6) {
document.getElementById("img1").src="image/dice6.jpg";
}
function Num2button() {
var button2 = "Are you sure"
alert(button2);
}
</script>
</body>
</html>
You can put your logic to assign the picture in your randomNumber function, the best would be to rename it to something like generateRandomPicture.
Then you need an element with the id you have specified and
also I would recommend that you use an eventListener instead of doing the inline scripting.
You can add .addEventListener() to your element.
document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);
function randomNumber() {
let number = Math.floor((Math.random() * 6) + 1);
if (number == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if (number == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if (number == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if (number == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if (number == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if (number == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
}
<head>
<title></title>
</head>
<body>
<p id="number"> </p>
<img id="img1"></img>
<button id="b"> Yes </button>
<button onclick="Num2button()">No</button>
</body>
I'm aware that the question is already answered and that you are new to this but this is a more scalable approach and looks a bit cleaner.
NOTE: This snippet assumes the images in the array in the correct order, from 1 to N.
let images = [
'https://via.placeholder.com/10',
'https://via.placeholder.com/20',
'https://via.placeholder.com/30',
'https://via.placeholder.com/40',
'https://via.placeholder.com/50',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length);
document.getElementById('img').src = images[index];
document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
As per epascarello's comment, this does not rely on the order of the images but they do have to be in the array.
var images = [
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length) + 1;
document.getElementById('img').src = images[index - 1] + '/' + index + '0';
document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
And if you always have a static number of images which are properly named you can even do away with the images array.
function setRandomImage() {
let rand = Math.floor(Math.random() * 6) + 1;
document.getElementById('img').src = 'https://via.placeholder.com/' + rand + '0';
document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>

Limit the amount of times a button is clicked

for my college project im trying to limit the amount of times one of my buttons is being clicked to 3 times, I've been looking everywhere for code to do it and found some yesterday, it does give me alert when I've it the max amount of clicks but the function continues and im not sure why, here is the code I've been using.
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has
drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total
of " + total;
if(total >21){
window.location="../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn "
+ card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch(button)
{
case "Stick":
if (total > 21) {
window.location="../End_Game/End_Lose_Bust.html";
} else if (total == 21){
window.location="../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location="../End_Game/End_Win.html";
} else if (total == compscore) {
window.location="../End_Game/End_Draw.html";
} else {
window.location="../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if(ClickCount>=clickLimit) {
alert("You have drawn the max amount of crads");
return false;
}
else
{
ClickCount++;
return true;
}
}
HTML
<!doctype html>
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick="NumberGen(); Total_Number(); countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Cheers in advance.
You are calling countClicks at the end of onclick. Change it to this:
if (countClicks()) { NumberGen(); Total_Number();}
Try this
var count = 0;
function myfns(){
count++;
console.log(count);
if (count>3){
document.getElementById("btn").disabled = true;
alert("You can only click this button 3 times !!!");
}
}
<button id="btn" onclick="myfns()">Click Me</button>
I have edited your code also following is your code
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total of " + total;
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn " +
card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch (button)
{
case "Stick":
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
} else if (total == 21) {
window.location = "../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location = "../End_Game/End_Win.html";
} else if (total == compscore) {
window.location = "../End_Game/End_Draw.html";
} else {
window.location = "../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if (ClickCount >= clickLimit) {
alert("You have drawn the max amount of crads");
return false;
} else {
NumberGen();
Total_Number();
ClickCount++;
return true;
}
}
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick=" countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>

How can I make my button compare the users answer with a "correct" answer?

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){}

Categories

Resources