Displaying Messages Without Using Alerts - javascript

I am working on a "guess my number" game and have ran into a problem. My game is supposed to select a random integer between 1 and 10 and allow the user to guess until they guess the correct number. After each guess, I'm supposed to display a message telling whether their guess was too high, too low, correct, or if they'd guessed that number before. I had the game working (except for displaying the array of previously guessed numbers) by using alerts to display the whether the user was too high, low, correct, etc like this.
if (guess == this.num) {
alert("Correct! It took you " + turns " tries to guess my number.");
...
}
However, going back over the directions I see that we are not supposed to user alerts or any other kinds of pop-ups. So I need to figure out how to display these messages on the screen rather than in an alert box.
Here is how I've attempted to do this without the use of alerts, but now the game is not working at all (nothing happens when I click either of the buttons):
<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 = [];
var 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);
}
catch(e) {
alert("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.");
alert("Correct! It took you " + this.turns + " turns to guess my number.");
tries.push(guess);
document.querySelector("#tries").textContent = tries.join(', ');
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
alert("Your guess is too high. Try again.");
document.querySelector("#tries").textContent = tries.join(', ');
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed this number. Try again.";
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
document.querySelector("#tries").textContent = tries.join(', ');
tries.push(guess);
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
}
};
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>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="reset" value="Reset Game" onclick="resetGame()"/>
</p>
<h3>How Did You Do?:</h3>
<p>
<input type="hidden" id="result" size="20" />
</p>
<h3>Here Are Your Guesses So Far:</h3
</body>
</html>
Is there any simple way to do this. I want the messages to display in a hidden text filed below the heading "How did you do?:" if that makes it a little clearer.
Here is a jsfiddle I made with my most recent code, http://jsfiddle.net/3p3f86fj/6/

You should add a div to your body with a unique ID, like <div id='result'></div> and then in your JS, reference it by getting the document by ID and your functions should change the text of the div to whatever you need it to be. Make a function to change the name if you want to abstract some of the logic away.

It's broken because of this line I believe:
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
You have a stray ) at the end.
I'm looking into other issues I see now.

Related

Adding Prompt() to High/Low Game

I created a high/low game that goes from 1-20. To take it a step further, I'm attempting to have the user pick the number to play against: pick between 1 - x (user input number). There are other parameters within the game that need to be tweaked as well with that change. I want to use specifically Prompt() for the user to select a number to play against, I'm just not sure how to add it as well as other changes that will need to be made. Any tips are appreciated!
var answer = Math.floor(Math.random()*20) + 1;
var no_of_guesses = 0;
var guesses_num = [];
function guessing(){
var user_guess = document.getElementById("guess").value;
if(user_guess < 1 || user_guess > 20 ){
alert("That number is not in range, try again!");
}
else{
guesses_num.push(user_guess);
no_of_guesses+= 1;
if(user_guess < answer){
outcome1.textContent = "Too low"
outcome2.textContent = "Number Of Guesses : " +
no_of_guesses;
outcome3.textContent = "Guessed Number Are: " +
guesses_num;
}
else if(user_guess > answer){
outcome1.textContent = "Too High"
outcome2.textContent = "No. Of Guesses : " +
no_of_guesses;
outcome3.textContent = "Guessed Number Are: " +
guesses_num;
}
else if(user_guess == answer){
outcome1.textContent = "You're Correct!!"
outcome2.textContent = "the Number was " + answer
outcome3.textContent = " You guessed it in " + no_of_guesses +"Guesses";
}
}
}
var outcome1 = document.getElementById("outcome1")
var outcome2 = document.getElementById("outcome2")
var outcome3 = document.getElementById("outcome3")
<div class="container">
<h3>Guess between 1-20!</h3>
<input type="text" placeholder="Choose a number" id="picknum"><br>
<button onclick="guessing()" id="my_btn">GUESS</button>
<input type="text" placeholder="Guess a number in range" id="guess"><br>
<p id="outcome1">Are you feeling lucky?</p>
<p id="outcome2"></p>
<p id="outcome3"></p>
</div>
I am not quite sure why you want to use prompt() for the user dialogue. My snippet uses the already provided <input> element instead and avoids unnecessary repetitions in the code:
const answer = Math.floor(Math.random()*20) + 1,
guesses=[];
const inp=document.getElementById("guess"),
out=document.querySelectorAll("[id^=outcome]");
function guessing(){
const n=inp.value;
guesses.push(n);
[`The number ${n} is ${n==answer? "correct!" : "too "+(n<answer?"low.":"high.")}`,
`You had ${guesses.length} guesses.`,
`The guessed numbers were: ${guesses.join(", ")}.`].forEach((o,i)=>out[i].textContent=o)
}
<div class="container">
<h3>Guess between 1-20!</h3>
<input type="text" placeholder="Guess a number in range" id="guess"><button onclick="guessing()" id="my_btn">GUESS</button><br>
<p id="outcome1">Are you feeling lucky?</p>
<p id="outcome2"></p>
<p id="outcome3"></p>
</div>
If you're willing to put up with its UI limitations, calls to prompt return the user's input; you could use your existing code, changing only the first line of guessing() to read
var user_guess = prompt("What is your guess?")
(Note that prompt returns a string; you'll want to use Number(user_guess) when doing mathematical comparisons.)

JavaScript code does not work as expected

So I made this little thing as I am quite new to programming, but when I open it in Chrome, I am able to type input but then nothing happens. Does anyone know how I can fix this code?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input type="submit" value="GO!">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low +1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
for (var i=0;i=0) {
if (guess>number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
}
if (guess<number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
}
if (guess==number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
}
}
}
startGame();
</script>
</body>
</html>
You've got a lot of problems, starting with a syntax error.
You have a submit button, but no form to submit. You really just need a button. But, even then, you have to set up a click event handler for it.
Then, your loop isn't configured properly.
You also are not accessing the data the user has typed into the textbox correctly - you need to get the value of the element.
Your if statements should be else if.
The b element should not be used just for presentation. HTML is a "semantic" language, meaning that you use a tag to describe the meaning (not presentation) of an element. For styling use CSS.
See comments inline below for details.
/* CSS is for presentation, not HTML */
#bold { font-weight:bold; }
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<!-- Don't use HTML for styling, use it for semantics. -->
<span id="bold">Guess:</span> <input type="text" id="guess">
<!-- You need a <form> if you have a submit button. For this, you just want a button. -->
<input type="button" value="GO!" id="go">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
// Get a reference to the output area just once
var output = document.getElementById("bold");
// Give the user 3 tries. Your loop wasn't configured properly.
for (var i=0; i < 3; i++) {
// You want to access the data in the textbox. That's the value
// Also, if the first condition isn't true, try the next and so on.
// This is done with else if branches
if (guess.value > number) {
output.textContent = "You're too high, try lower!";
} else if (guess.value < number) {
output.textContent = "You're too low, try higher!";
} else if (guess.value == number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
break; // Get out of the loop because the game is over.
}
}
}
// Set it up so that clicks on the button run the function
document.getElementById("go").addEventListener("click", startGame);
</script>
</body>
</html>
you have some errors:
this doesnt work, it wont loop. actually, why do you want to loop?
for (var i=0;i=0) {
this will run the function once, this means when the user writes the value it wont be checked
startGame();
the button doesnt do anything, also it has a submit and you don't have any forms:
input type="submit" value="GO!">
on each if, the conditions are exclusive, use if/else
below is a working code:
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input value="GO!" onclick="checkGuess()">
<script>
var number = 0;
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
number = getRandomNumber(1, 10);
}
function checkGuess() {
var guess = document.getElementById("guess").value;
if (guess > number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
} else if (guess < number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
} else if (guess == number) {
alert("You're correct, the number is " + number + "!!!");
alert("Thanks for playing my game and have a good day!");
}
}
startGame();
</script>
</body>
</html>
Although i have no idea about what your program does. you have a syntax error at
for (var i=0;i=0) {
and also you should bind an event to that button rather than doing a submit.

Javascript number guessing game - setting up the counter & while loop

I'm trying to create a random number guessing game in Javascript that compares user input to a number generated with the math.random method. I'm confused by how to set up the counter the right way. I have to validate the number, display each guess with "too high," "too low" or "you win" then show the 'secret' number at the end. Not sure what I'm doing wrong! Right now it is overwriting each answer and the counter is staying at #5.
function myFunction() {
var userInput = document.getElementById("text").value;
// test for valid input number from 1 to 999
if (userInput < 0 || userInput > 999) {
alert("Your number must be from 1 to 999");
} else {
alert("Input OK");
} // end function myFunction
var randomNum = Math.floor(Math.random()* 999)+1;
var userInput = document.getElementById("text").value;
var counter = 0;
var totalGuesses = 0;
while (totalGuesses <= 5) {
counter++;
document.getElementById('loopResults').innerHTML = "<p>You have made" + counter + "guesses</p>";
if (userInput < randomNum) {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too low!</p>";
} else {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too high!</p>";
}
}
}
</script>
</head>
<body>
<h1>Guessing Game</h1>
<p id="loopResults"></p>
<form action="" method="post" enctype="multipart/form-data" name="userData">
<input name="userInput" id="text" type="text" size="10" /> - Enter a number from 1-999!</form>
<p><span style="background-color:#066aff; color: #ffffff; padding: 5px;" onclick="myFunction();" >enter number</span>
</p>
</body>
You don't need a while loop here. What happen is simply once it enters the while loop, it increments your counter to 5.
Take the while loop out and it will do what you want it to do.
And I don't think you need the totalGuesses
Edit:
So I further look into your code. In order to do what you want it to do, instead of putting everything in your myFunction, here are the steps:
create a random_number
create a counter
a function that is bind to onclick, this is where the main logic is. And here's what you need to do.
get the input result from the input field, and parse it to Integer
compare with the stored random_number
if correct, alert ok
if not, increment the counter
if the counter reaches limit, alert and show result
Not going to write down the code, and I think you can figure it out.

JQuery random number guessing game: loop woes

I am trying to make a simple number guessing game: a random number between 1 and 9999999999 is generated and printed to the console. I want the user to input their guess in a form - and keep looping guesses until the guess matches the random number.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Number Guess</title>
</head>
<body>
<!--text display/button -->
<p>Try and "guess" the random number! Click "Generate new random number" to start"</p>
<div id="out1"></div>
<form id="promptUser">
Your guess:
<input type="text" id="inUserGuess">
<input type="submit" value="Submit">
</form>
<br>
<button id="btn1">Generate new random number</button>
<div id="in1"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>/*SEE SCRIPT BEOW */</script>
</body>
</html>
And here is the javascript/jquery inside:
$(document).ready(function() {
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var win = false;
while (win = false) {
$('#promptUser').on('submit', function(e){
e.preventDefault;
var userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
});
/*yes: "congrats! start again"*/
if (userGuess == randNum){
console.log("User guess is correct");
alert("You got it! Try another round.");
win = true;
}
/*no: "not quite. guess again."*/
else {
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
win = false;
}
}
In order to keep the user guessing until they get it right, I put the guess input inside a while loop and used and if/else statement to determine whether their guess matches the random number.
It seems as though the code gets messed up somewhere before the if/else statement- the console log never shows up. Instead, a new random number is generated when submit is pressed.
I know the syntax of gathering input works - before I attempted to give the user infinite guesses the if statement ran fine (though a new random number was automatically generated after each "play", regardless of correct/incorrect guess)
I feel stupid asking this - but I've been fiddling with it for hours.
[[EDIT]] I now have the submit button event handler doing two things: storing the user input to userGuess and checking to see whether or not it matches randNum, but still is stuck in an infinite loop:
<script>
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var userGuess = "";
do {
$(document).ready(function() {
$('#promptUser').on('submit', function(e){
e.preventDefault;
userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
if(userGuess == randNum){
console.log("user guess is correct");
alert("That's right! Play again.");
}
else{
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
}
});
});
}
while (userGuess != randNum);
/*generate new random number each on button click */
$('#btn1').on('click', function(){
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum); /*(return random number to console for cheating)*/
});
</script>

validate field length

i want my roll number length should be equl to 4 and the data inserted can only be integer..
how can it be possible through java script
i am trying this code but it is just checking it, if roll number is greater then 4 it displays error but also insert the roll number
function rollnumber(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert(" nter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
rollnumber(document.getElementById('rollnumber'), 1, 4);
return true;
It confuses the javascript rollnumber is both a function name and an element id.
The function needs to be executed on a form when it submits otherwise it will continue submitting instead of stopping
Here is the fixed code. Tested.
<form onsubmit="e_rollnumber()">
<input type="text" id="rollnumber" />
<input type="submit" value="Click here to roll the number" />
</form>
<script type="text/javascript">
function e_rollnumber(){
var len = {min:1,max:4};
var input = document.getElementById('rollnumber');
if(input.value.length>=len.min && input.value.length<=len.max) return true;
alert("Please enter between " +len.min+ " and " +len.max+ " characters");
input.focus();
return false;
};
</script>

Categories

Resources