this is my first question on stack overflow, I have only been coding for a few months and I know I am probably just missing something simple here. I am trying to create a simple program for learning purposes, computer auto picks number between 1-100, user then picks number and is alerted if their choice is hot or cold in relation to the computer number.
I am trying to pass the users answer from a form field into a JavaScript variable, then run the function to test their answer when a button is clicked. I am using jQuery for both of these.
Here is the application live: http://keithlamar.github.io/HotOrCold/
Here is my HTML:
<form>
Your Number <input id="guess" type="number" name="yournumber"><br>
</form>
<p id="pick">Click Here</p>
Here is my JavaScript:
var userNum = $('#guess').val();
var comNum = Math.floor(Math.random()*101);
var difference = function (a,b) {return Math.abs(a - b)};
var askNumber = function(){
if(userNum == comNum){
alert("You got it! You Win!")
}
else if(difference(userNum,comNum) < 5){
alert("Very Hot!");
}
else if(difference(userNum,comNum) < 10){
alert("Hot!");
}
else if(difference(userNum,comNum) < 20){
alert("Warm!");
}
else if(difference(userNum,comNum) > 20){
alert("Very Cold!")
}
else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function(){
$('#pick').click(function(){
askNumber();
});
});
It seems like the var userNum is not getting a value from the input. I think it may have something to do with nesting of functions within functions, but I am not entirely sure!
Thanks for any input!!