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

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.

Related

JavaScript: Generating a random number with user input from a prompt box (number guess game)

The user has to guess a randomly generated number based on the highest value THEY input into a prompt box. Example (from 1 to ?)
I have to use a prompt and the value cannot be a decimal or string.
I'm not sure how to validate that or just not allow the user to input an invalid entry.
I am having issues reusing the number they input in the function for random number generation let num = Math.floor(Math.random() * inputMaxNumber + 1); in the game. I tried converting the value from a string to a number but that didn't work either.
This is what I have so far:
//prompt for max number the user inputs
function maxNumber() {
let inputMaxNumber = prompt ("Enter the maximum number the game can pick", " #");
if ( inputMaxNumber > 1) {
document.getElementById("maxNumber").innerHTML = "Guess a number between 1 and " + inputMaxNumber;
}
else {
alert("You must enter a positive whole number greater than 1");
}
console.log(inputMaxNumber);
}
inputMaxNumber = Number(document.getElementById("maxNumber").value); //converts this to a number from a string
// array that stores guesses
var numGuessArray = []
//validates user input for guesses (no decimals, strings, or negative numbers)
function onlyNumbers(num){
if ( /[^0-9]+/.test(num.value) ){
num.value = num.value.replace(/[^0-9]*/g,"")
}
}
//get user input to use in random number generation
// random value generated based on user input (a) new variable is num
let num = Math.floor(Math.random() * inputMaxNumber + 1);
console.log(num);
//counts the number of guesses for correct guess
var guess = 1;
//store counts and numbers guess in an array (don't count invalid guesses)
function do_guess() {
let guess = Number(document.getElementById("guess").value); //converts this to a number from a string
let message = document.getElementById("message");
//show on console
console.log(guess);
//hints about guess
if(guess == num) { //correct guess with count
message.innerHTML = "You got it and it took " + guess + " guess!";
}
else if (guess > num) { //number too high
message.innerHTML = "No, try a lower number";
}
else {//number too low
message.innerHTML = "No, try a higher number";
}
//you already guessed that number NO COUNT
}
//guess button used to guess
//use an array to keep track of the guess
<div class="container">
<h1>Higher - Lower</h1>
<p>Guess a number</p>
<div class = "row">
<div class ="col-lg-3 col-md-6">
<form>
<div class ="form-group">
<!-- This button triggers the prompt to allow the user to enter the max number-->
<input type ="button" value = "Click To Start" onclick = "maxNumber()";/>
</div>
<div class ="form-group">
<label> Your Guess:</label>
<!-- Prevents user from inputing decimals with onkeyup-->
<input type ="text" onkeyup="onlyNumbers(this)" id="guess" class ="form-control">
</div>
<p id = "maxNumber" ></p><!--Outputs maximum number range the user selected-->
<!--Button calls guess funciton when clicked-->
<button type="button" class ="btn btn-primary" onclick = "do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p> <!--Where message will go-->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
Inside function maxNumber() you define inputMaxNumber locally let inputMaxNumber = prompt(...); so its value is lost when the function execution ends.
Additionally, the code where you generate the random number is executed only once, upon page load let num = Math.floor(...);. It's not executed after user enters his choice for the maximum.
Solution:
define num globally
assign the random value to it inside maxNumber()

Trying to create a random game but doesn't seem to work

Under my form action, I called the textbox and buttons. It was suppose for the user to key in 2 values one being the highest value and another being the lowest value, it will then generate a random value between the lowest and the highest. The user will than guess the number if its correct it will print out the message correct
<form action="random" method="get" onSubmit="return validate()">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<br/><span id="numbers1"></span>
<br/><input id="rand" type="submit" value="submit" onclick="Random()"><br/>
<input id="guess" type="text" value="Random Number Generator">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</form>
My script consist of the methods and functions to use, I think the problem lies at the RandomNumber() function, im not sure where did I go wrong, but please assist me
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
This is the function to generate a random number in between the lowest number and the highest number.
function Random()
{
var value1 = document.getElementById("digit").value;
var value2 = document.getElementById("digit1").value;
minvalue= Math.ceil(value1);
maxvalue= Math.floor(value2);
var random = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
document.getElementById("guess").value=random;
}
And this is the part where I assume it may have cause the entire program to stop working, its after I wrote down this codes and my web page doesn't perform the way I want it to be.
function RandomNumber()
{
var value3 = document.getElementById("digit").value;
var value4 = document.getElementById("digit1").value;
minvalue= Math.ceil(value3);
maxvalue= Math.floor(value4);
var random1 = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
var maxtries=5;
var counter=0;
var true=document.getElementById("textbox").value;
while(true!=random1)
{
document.getElementById("total").value=total;
counter +=1;
if(counter>maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
if(true==random1)
{
document.getElementById("correct").innerHTML="Correct"
}
}
}
When I look at your code I see a couple of red flags.
E.g. true is a reserved keywoard in JS, you can't assign a value to it:
var true=document.getElementById("textbox").value;
This must throw an error in your development console.
Also in your loop while(true!=random1) neither true or random1 are reassigned, so if true in the beginning, the condition will never become false, hence the loop is never left in this case!
In general you should try to narrow your issue down, look at the errors and rather ask for help on smaller snippets where you ask concrete questions. With a statement like my web page doesn't perform the way I want it to be it is hard to provide help.

This will not return the "if" statement, even though terms are met

This code should detect where a number is above 1,000,000,000 and below 9,999,999,999. I try to input numbers between these 2 values, but it still returns the else statement. Where is the problem in this code?
<html>
<head>
<title>Checking with RegExp</title>
</head>
<body>
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
<script>
function checknumber() {
var tendigitnum = document.getElementById("inputnumber")
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
}
else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
</script>
</body>
</html>
You're comparing an HTML element to a number. You want to compare a number to a number, by:
Using the .value property on the element to get the string, and
Parsing that string to a number (you have lots of different ways to do this depending on your use case; see this answer for a list of them)
For instance:
var tendigitnum = Number(document.getElementById("inputnumber").value);
Live Example:
function checknumber() {
var tendigitnum = Number(document.getElementById("inputnumber").value)
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
} else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
On modern browsers you could use a number input:
<input type="number" id="inputnumber">
and use its valueAsNumber property instead of value, since valueAsNumber will already be a number. You can even add the range validation to the input. More on MDN.
You need to check the value in your element, in your code you are checking element

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

JS Calculation assistance

I'm having some issues with my code, I'm creating a site to get it to calculate mortgages with down payments of:
3% of the first $25,000
Insures home mortgages requiring a down payment as follows:
3% of the first $25,000
5% of the remainder
The input consists of a SSN and a mortgage amount. I wanted it to print the applicant’s SSN and the amount of down payment required. Reject any applications over $70,000. Don’t forget to validate your input. If the input is not good, and I want it to display an error message and ask for the input data again.
<html>
<head>
<title>Mortgage Charges</title>
<script type="text/javascript">
// Program name: FHA
// Purpose: print the applicant’s SSN and the amount of down payment required
// Date last modified: 3/29/12
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
var mortgage = 0;
if (mortgage <= 25000) {
amtOwed = 0;
}
else if (mortgage >= 5%) {
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
window.onload = function() {
document.frmOne.onsubmit = function(e) {
mortgage();
return false;
};
};
</script>
</head>
<body>
<form name="frmOne">
Enter your SSN:<input type="text" id="ssn" /><br />
Mortgage amount:<input type="text" id="mortage" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I'm afraid I can't fathom your logic. How do you expect this to work?
Let me break down what your current code does:
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
// Get the value from the text box, and convert it to a number. That's good.
var mortgage = 0;
// Initialise a variable. Fair enough.
if (mortgage <= 25000) {
// You JUST set morgage=0. How can it be anything but less than 25k?
amtOwed = 0;
// You are overwriting the value you got from the form with 0
}
else if (mortgage >= 5%) {
// Okay, first of all this else will never be reached, see comment above.
// Second... 5% of what, exactly? If you want 5% of a number, multiply the number by 0.05
// Third, what's the point of this block if there's no code in it?
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
Basically, your code can be simplified to:
function morgage() {document.frmOne.mortage.value = 0;}
Because that's all it does.
I don't really understand exactly what you're doing, but hopefully explaining what your current attempt is doing will help you to find the answer.

Categories

Resources