1 year ago
#332038
Koryn Pascoe
Can't get textbox input converted to an integer?
I am trying to create a program that takes a user input number and compares it to a randomly generated number until the user guesses the correct number. I was having a problem where my user input number is showing up undefined while I am debugging my program but I used parseInt and fixed the issue. Now it seems it is an issue with my if else statement because I get the right use input number back now when I run a debug on my code but it now when I run it, even when I enter 1000 as my guess, it always gives me "Your guess is too low! Try a higher number."
var guessNum;//user input guess
function randomNumber(guessNum1)
{
guessNum = document.getElementById( "numInput" ).value;//getting value of user input
var guessNum1 = parseInt(guessNum);//change user input to integer
var num = Math.floor( 1 + Math.random() * 1000 ); //random number generator
if (num == guessNum1)
{
messages.innerHTML = "Congratulations! You guessed the number!";
}
else if (num < guessNum1)
{
messages.innerHTML = "Your guess is too high! Try a lower number.";
}
else (num > guessNum1)
{
messages.innerHTML = "Your guess is too low! Try a higher number.";
}
guessNum = document.getElementById( "numInput" ).value = "";//clears the textbox on screen
}
function start()
{
var guessButton = document.getElementById( "guess" );//variable for clicking button
guessButton.addEventListener( "click", randomNumber, false);
//event listener for button that starts randomNumber function
messages = document.getElementById( "messages" );
}
window.addEventListener( "load", start, false);//starts start function on screen load
<h1>Guess the Number!</h1>
<h3>Enter in a number between 1-1000 in the textbox and hit submit </h3>
<form action = "#">
<input id= "numInput" type="text" >
<input id= "guess" type="button" value="Guess" >
</form>
<p id= "messages">Enter a number to start the game </p>
javascript
html
forms
getelementbyid
0 Answers
Your Answer