Page doesn't load when I set variable to 0 in Javascript - javascript

var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
while (attempts < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
while learning how to use a random number generator, I wantd to add a while loop and give 3 attempts to choose from a random number.
When I create a variable to set the number of attempts, if I make the variable equal to 0, my page doesn't load, but if I leave the variable empty without a value, the script doesn't run.
Any ideas of why this may be happening?
var randomNumber = Math.floor(Math.random() * 6);
var x = 0
var maximum = 3
while (x < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>

Your while loop runs synchronously, during pageload. The script never finishes, because the while loop's condition is never negated, so control is never yielded back to the browser to repaint the page, so the user never has a chance to input a number or click on the button.
While you could keep using while by promisifying the onclick and awaiting a Promise, it'd be better to create the handler outside, once, and have it check if the attempts are maxed out.
You also need to use consistent variable names: either use x or attempts, not both:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
document.getElementById("submit").onclick = function() {
if (attempts >= maximum) return;
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
<input type="text" id="input">
<button id="submit">Submit</button>

You could disable the button after the maximum number of attempts has been reached, like:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0;
var maximum = 3;
document.getElementById("submit").onclick = function(e) {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
if (attempts === maximum) e.target.disabled = true;
};
<input type="text" id="input" />
<button id="submit">Submit</button>

Related

I'm a beginner and I don't understand how my code works (javascript)

I want user to guess how many fingers are there (Math.random()), but it does not work the way I expect it to and I can't find the mistake.
This is all in a <body> tag:
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>
<script>
var fingers = parseInt(Math.random()*6);
var userInput = document.getElementById("userInput").value;
var i = 0;
var num = document.getElementById("numberOfTries");
function check(){
if (userInput == fingers)
{
alert("You got it!");
}
else{
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
</script>
So, the way I see this: when the page loads it creates a random number (fingers), and then I just compare that number to the number in input.
Why doesn't it work?
You had just a small error. You only checked their input once. See I moved to the function scope and now it works.
var fingers = parseInt(Math.random() * 6);
console.log(fingers);
var i = 0;
var num = document.getElementById("numberOfTries");
function check() {
// This was in the wrong place. We need to check user input each time.
var userInput = document.getElementById("userInput").value;
if (userInput == fingers) {
alert("You got it!");
} else {
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>

Compare generated letter with user input

My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input

Guessing Game in Javascript

What I'm trying to do is make a simple guessing game where the user can any the number without limit but will be graded at the end when the guessed the number correctly based on the number of their guesses. However, with my code when I enter a number and press the button to multiple times the hint changes from "Higher" to "Lower" even if the number is not changed also the message that should be displayed when the number is guessed correctly is not showing. Here's my code, I'm a beginner so there's bound to be errors in the code and any help is appreciated.
<fieldset>
<input type="number" id="guess" />
<button onClick="checknum();">Check Number</button>
</fieldset>
<fieldset>
<p>Your current status:</p>
<output id="status_output">You have yet to guess anything.</output>
</fieldset>
<script type="text/javascript">
function checknum(){
var randomNumber = Math.floor((Math.random() * 100) + 1);
var guessNumber = document.getElementById("guess").value;
//var guessNumber = parseInt(guess.value);
var statusOutput = document.getElementById('status_output');
var counter = 0;
var isguessed = false;
do {
counter = (counter + 1)
if (guessNumber < randomNumber) {
statusOutput.value = ("Higher");
}
else if (guessNumber > randomNumber) {
statusOutput.value = ("Lower");
}
else if (guessNumber = randomNumber) {
set (isguessed = true());
statusOutput.value = ("Correct" + mark());
}
}
while (isguessed = false);
}
function mark(){
if (counter < 10){
statusOutput.value("Excellent");
}
else if (counter > 10 && counter <20){
statusOutput.value("Okay");
}
else
statusOutput.value("Needs Practice");
}
</script>
In your while you are assigning false to the variable named isguessed.
You want to do while (isguessed === false) instead. This will check if isguessed is set to false
isguessed = false : assigns the varibles isguessed to false
isguessed === false : a boolean expression return true or false

How do I make a document wait for an assigned input value?

I am writing a number guessing game. Every time I run the document it automatically goes to my outer else statement and I know why, but I can't figure out how to make it wait for an input value of the textbox. I want to set "guess" = to the value of the text box by pressing submit which will then enter the if statements. At the moment it is automatically setting to null and causing the error. Here is the code.
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
Have you tried to disable the button, then add an onChange event to your text box so that you can enable the button once you have the desired input? You will need to add an ID or Name value to your button so it can be accessed? And to add what #LGSon added:
if(myguess <= last && myguess >= first && cont == true){, you check the variable cont, which I can't find in your code, so if it is not declared and set somewhere, you code will always take the outer route.
Second, you need to split your search function into 2 functions, one that generates the input, one that runs when someone entered a value (which can be fired on keypress or with a button)

Problems with Javascript Game

I'm working on what should be an extremely simple "guess my number" game in Javascript, however, I can't get it to work correctly.
The program is supposed to choose a random integer between 1 and 10 and allow the user to try and guess that number as many times as it takes to get it right. If the user guesses a number that's lower than the correct one, the program is supposed to display a "your guess is too low" message, this is the same for when the guess is too high, or correct. The program must display the message on the webpage, not in an alert or any type of pop-up. Also, the program is supposed to keep a running list of the numbers that have been guessed by the user and display them on the page each time the user makes a guess (I want this list to display below my heading "Here are the numbers you've guessed so far:"). And finally, the program is supposed to display a "you already tried using that number" message if the user tries to input a number that they've already used.
Here is my code, along with a JSfiddle I've created and am still playing with.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type = "text/javascript">
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random(), 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1 {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
}
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
}
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<div id = "result">
<input type = "text" id = "result" size = "20" />
</div>
<h3>Here are the numbers you've guessed so far:</h3>
</body>
</html>
http://jsfiddle.net/v09ttL74/
As you should be able to see from the fiddle, nothing is happening when I click either one of the buttons, so I'm not really sure where the problem is. I am getting a few errors when I select the JShints option on the fiddle, but most are things like "Missing semicolon" in places where there's not supposed to be a semicolon, like an one line where all I have written is
else {
Any suggestions would be greatly appreciated. I feel like this is just a really simple project that I am over-thinking since I'm stressed about it not working.
There's a lot of issues in your code. Just to mention a few...
1- Unclosed parenthesis here
tries.push(document.getElementById("guess").value;
it should be...
tries.push(document.getElementById("guess").value);
2- Expression not terminated with a close parenthesis here
else if(tries.indexOf(guess) != -1 {
it should be...
else if(tries.indexOf(guess) != -1) {
3- Wrong declaration of functions inside a function
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
I could be going forever but, really, the errors are a bit obvious
Alright as some of the answers must have already given you an idea of how many mistakes your Script as well as HTML code had.. from missing parenthesis to same ids to missing elements. Well i have corrected them and it's working now:
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<input type = "text" id = "result" size = "20" />
<h3>Here are the numbers you've guessed so far:</h3>
<p id='tries'></p>
Script:
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
alert(guess+ ' '+this.num);
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
else if(guess < this.num){
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
}
}
function display() {
var number = "";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
See the DEMO here

Categories

Resources