Looking for some guidance from those more knowledgeable than myself.
I'm writing a program that will prompt the user to click a button, which will then generate a random integer from 1 to 100.
I can manage that part fine. What I am struggling with is making the program print what range this random integer is in i.e. i<=33.
For example, when I click the button I want to see:
"10 is a number less than 33"
or
"55 is a number between 33 and 66"
Here is my code so far, I have put the code I am having problems with in comments.
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<title>question2</title>
</head>
<body>
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
}
// if (myFunction <= 33) {
// text += ("<br>" + i + " is a number less than or equal to 33");
// }
// if (myFunction > 34 and i < 65) {
// text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
// }
// if (my Function >= 66) {
// text += ("<br>" + i + " is a number greater than or equal to 66");
// }
</script>
</body>
</html>
Thanks guys.
You could test and if true display the result and exit.
function getRandom() {
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
document.getElementById("demo").innerHTML += i + " is a number less than or equal to 33<br>";
return;
}
if (i < 66) {
document.getElementById("demo").innerHTML += i + " is a number between 33 and 66 (exclusive)<br>";
return;
}
document.getElementById("demo").innerHTML += i + " is a number greater than or equal to 66<br>";
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="getRandom()">Click here</button>
<p id="demo"></p>
Did you mean something like this:
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
}
The problem is you are calling variables from inside myFunction() outside of that function. Examples include i and myFunction(). It would be better to put the if else statements inside the main function.
function myFunction() {
var demo = document.getElementById("demo");
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
demo.innerHTML = i + " is a number less than 33";
}
else if (i < 65) {
demo.innerHTML = i + "is a number between 33 and 65";
}
else {
demo.innerHTML = i + " is a number greater than or equal to 66";
}
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
Your function isn't what you should be comparing against in your if statements.
But, I did throw something together let me know if this is what you were looking for.
You were on the right track. Also on the middle comparison I changed you "and" to a shortcircuit "&&".
JSfiddle: https://jsfiddle.net/xew8dvbd/
$(document).ready(function() {
function myFunction() {
var i = Math.floor((Math.random() * 100) + 1);
var text = "";
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
};
$("#submit").click(myFunction);
});
Not sure why, but I had to do this as a function expression rather than a function definition to make it work. Oddly, that's the second time this one worked as a gotcha in the last hour.
myFunction = function() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
switch (true) {
case (i < 20):
console.log(i + " is less than 20.");
break;
case (i < 40):
console.log(i + " is between 21 and 40.");
break;
case (i < 60):
console.log(i+ " is between 21 and 60.");
break;
default:
console.log(i+ " is over 60.");
}
};
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
Related
I want to create a "Guess the numbers game" where you guess a random number within a certain amount of attempts.
I struggle with:
(Must have)
1. Progressing in the loop after the alert (which shows you if your guess was to high, too low, or not a number.
(Nice to have)
2. Resetting the game if you managed to guess the number or ran out of attempts. Resetting means to restore the original amount of guesses and zeroing your attempts. Maybe just a command that refreshes the page.
I'm - after years of break after my first attempts - new to coding.
Here is access to my project: https://glitch.com/~gravel-pyrite
I think this is the relevant loop/conditions engine where I mess up:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
document.getElementById("submit").onclick = function() {
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I expect that after the alerts, I can enter a new value, instead I get stuck in an "alerts loop".
EDIT: I've updated my code now. Reloading the page in after succeeding using up all tries works well.
One thing open:
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
won't only show after the first time the button was submitted.
This is the HTML:
<body>
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button onclick="resetGame()">Reset Game</button>
</body>
Adjusted your code
See fiddle example: https://jsfiddle.net/u0cmtg7j/1/
You don't need a loop, do everything in you submit event.
Also move your DOM manipulation code inside your submit event since you want to update the HTML every time your result changes.
Suggestions:
pack you DOM/HTML manipulation code in a function so that is nice and re-usable.
JS
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Prompt that asks user to guess a number between x / 10
//Check if number is correct
//If wrong, prompt them to guess again unti they run out of guesses
//If correct, tell them they won, the number of attempts and thank you
document.getElementById("submit").onclick = function() {
var attempts = document.getElementById("guessInput").value;
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter > maxTries) { //If running outs of attempts, break out of loop
alert("You used up your maximum tries.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
}
function resetGame() {
}
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
HTML
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button>Reset Game</button>
There is no need for you to loop within your onclick callback method. By looping you're going to keep checking the value in guessInput without letting the user change their guess, and so the same if block will always run until the player is out of guesses. Instead, you need the click method to control when and how many times the code within your function runs, as it will allow the user to change their guess:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
console.log(randomNumber);
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries.");
// resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
//resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
}
<input id="guessInput" type="number" />
<button id="submit">Guess</button>
This is my result. I'm sure things can be improved but all works functionally:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
//The code
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I saw your question yesterday, I prepared an answer for you but I found that you have deleted your question :) .
I use console.log(someVariable); before using it in my code so that I make sure it exists and not null or undefined
when I did this with your code I found that the variable 'random' existed when I declared it and assign it, but inside the event handler function it becomes 'undefined' because the function is asynchronous
the working code is the following with simplified logic
var rangeMin = 0;
var rangeMax = 10;
var remainingGuesses = 4;
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
var random;
var guessesMade = 0;//the user hasn't guessed anything yet os we'll declare and assign the variable as zero
document.getElementById("submit").onclick = function guess() {
//this is a new guess from the user, lets increase the counter of guesses made and decrease remaining guesses
guessesMade++;
remainingGuesses--;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
//lets assign the variable random a number
random = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
//lets get what the user guessed
var userGuess = document.getElementById("guessInput").value;
if (random == userGuess) {
alert("CONGRATULATIONS!!! GUESSES NEEDED: " + guessesMade);
//Resetting:
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//So the user didn't guess it right, there two scenarios:
//1- user already consumed his chances, we'll alert him about it and reset the game
//2- user still has guesses to make, we will test and advise him
if (remainingGuesses == 0) {
// scenario (1-)
alert("SORRY, YOUR RAN OUT OF GUESSES. LETS PLAY AGAIN!");
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//scenario (2-)
//we will check the value of his guess and advise him
if (random > userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS SMALLER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A HIGHER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else if (random < userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS HIGHER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A SMALLER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
}
}
}
My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help.
The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="black" >
<font color="white" >
<progress id="myProgress" value="10" max="10"></progress><br>
<p id='demo5' ;></p>
<button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img
id="enemy1" src="Game_Images/smiley_1.png"></button>
<button id="spriteTest" type="button" onclick="imageSwap2()"><img
id="enemy2" src="Game_Images/smiley_1.png"></button><br>
<button id="upgrade" type="button" onclick="upgradeClickDamage()">
</button>
<button type="button" onclick="moreGold()">More Gold</button><br>
<button type="button" onclick="saveGame()">Save Game</button>
<button type="button" onclick="loadGame()">Load Game</button>
<p id='demo' ;></p>
<p id='demo2' ;></p>
<p id='demo3' ;></p>
<p id='demo4' ;></p>
<script>
var clickDamage = 1;
var gold = 0;
var stage = 1;
var enemyNum = 1;
var enemiesTotal = 10;
var enemiesKilled = 0;
var cost = 100;
var enemyHPTotal = 10;
var enemyHPCurrent = 10;
document.getElementById("upgrade").innerHTML = "Upgrade click damage for:"
+ cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:"
+ enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:" +
enemyHPCurrent + "/" + enemyHPTotal;
function imageSwap() {
var image = document.getElementById("enemy1");
if (image.src.match("Game_Images/smiley_1")){
image.src="Game_Images/smiley_2.png"
}
else if (image.src.match("Game_Images/smiley_2")){
image.src="Game_Images/smiley_3.png"
}
else {
image.src="Game_Images/smiley_1.png"
}
}
function imageSwap2(){
var image2 = document.getElementById("enemy2");
if(image2.src.match("Game_Images/smiley_1")){
setTimeout(image2.src="Game_Images/smiley_2.png", 300);
}
else if(image2.src.match("Game_Images/smiley_2")){
setTimeout(image2.src="Game_Images/smiley_3.png", 300);
}
else {
setTimeout(image2.src="Game_Images/smiley_1.png", 300);
}
}
function dealDamage() {
document.getElementById("myProgress").value -= clickDamage;
//If enemy is hit but does not die
if(document.getElementById("myProgress").value >= 1){
enemyHPCurrent = document.getElementById("myProgress").value
enemyHPTotal = document.getElementById("myProgress").max
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If enemy is killed and there are remaining enemies in the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum < 10) {
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyHPTotal = document.getElementById("myProgress").value;
enemyNum += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled += 1;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If the enemy is killed and it is the last enemy of the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum == 10) {
document.getElementById("myProgress").max += 1;
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyNum = 1;
stage += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled = 0;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPTotal = document.getElementById("myProgress").max;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
}
function upgradeClickDamage() {
if (gold >= cost) {
gold -= cost;
clickDamage += 1;
cost += 100;
document.getElementById("messageBox").innerHTML =
"Congratulations!!! You just upgraded your click damage."
document.getElementById("upgrade").innerHTML = "Upgrade click damage
for:" + cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
}
else if (gold < cost) {
document.getElementById("messageBox").innerHTML = "You don't have
enough gold for this upgrade."
}
}
function moreGold() {
gold += 100;
document.getElementById("demo").innerHTML = "Gold: " + gold;
}
function saveGame(){
//save all vars
localStorage.setItem('CLICKDAMAGE', clickDamage);
localStorage.setItem('GOLD', gold);
localStorage.setItem('STAGE', stage);
localStorage.setItem('ENEMYNUM', enemyNum);
localStorage.setItem('ENEMIESTOTAL', enemiesTotal);
localStorage.setItem('ENEMIESKILLED', enemiesKilled);
localStorage.setItem('COST', cost);
localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal);
localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent);
}
function loadGame(){
//load all vars
clickDamage = localStorage.getItem('CLICKDAMAGE');
gold = localStorage.getItem('GOLD');
stage = localStorage.getItem('STAGE');
enemyNum = localStorage.getItem('ENEMYNUM');
enemiesTotal = localStorage.getItem('ENEMIESTOTAL');
enemiesKilled = localStorage.getItem('ENEMIESKILLED');
cost = localStorage.getItem('COST');
enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL');
enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT');
}
</script>
<div id="messageBox"></div>
</font>
</body>
</html>
I expected all variables to function properly after loading.
gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.
(This will restate a bit of what you hypothesized in your question for the sake of completeness)
If you look at the documentation for Storage.getItem(), it says:
Return value
A DOMString containing the value of the key. If the key does not exist, null is returned.
This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console:
localStorage.setItem("test", 1);
> undefined
localStorage.getItem("test");
> "1"
When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +.
+localStorage.getItem("test");
> 1
The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value.
So you are trying to concatenate string and number "1" + 1 === "11".
To prevent this behavior you need to manually convert values to stringified JSON:
localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage));
And then parse it back:
clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));
First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check
for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/
Everything runs correctly, but I want to add a few things. At the very end of the function I want to change the height of the canvas by comparing how many you got correct out of the amount that you wanted to answer, but with a percentage. Sorry if this is difficult to understand.
JavaScript:
<script type="text/javascript">
function myFunction() {
score = 0;
questionAmount = prompt('How many question would you like to solve?');
for(i = 0; i < questionAmount; i++) {
var x = Math.floor(Math.random() * 13);
var y = Math.floor(Math.random() * 13);
question = prompt('What is ' + x + ' * ' + y + ' = ?');
if(question == null || isNaN(question)) {
break;
}
if(question == x * y) {
score++;
}
}
alert('You got ' + score + ' out of ' + questionAmount + ' correct.');
}
</script>
HTML:
<canvas id="content"></canvas>
<br />
<button onclick="myFunction()">CLICK</button>
Just create the percentage and apply it:
var correctPercent = (parseDouble(score) / parseDouble(questionAmount)) * 100;
//change the target elements style, apply above variable
document.getElementById("content").style.height = correctPercent + "%";