Javascript Code for pick random number game not working - javascript

I'm new at coding, just started learning javascript and I wanted to try and write a simple game to test out my skills. I apparently have very few because the code for a basic game doesn't work.
In this game, the user is prompted to generate a random number by clicking a button, once they click the button, they can enter their guess and submit. Once they submit their guess, they can click the last button to see if their guess was correct.
Unfortunately, when I try to run the code, it skips over the if else statement, no matter what I plug in and I can't figure out why. I would much appreciate the help. Please don't just give me a better code, I know there are a ton of easier ways I could have written it. But being able to spot and sort out bugs on a simple program like this would probably help me with spotting bugs in my own code in the future.
Thanks!!!
This is the code....don't make fun of me, I'm new to this.
<!DOCTYPE html>
<html>
<body>
<button onclick="genNum()"> Random Number </button>
<p id="demo"></p>
<form id="form1">
Guess: <input name="userGuess" type="number" size="20">
</form>
<button onclick="outputnum()"> Submit </button>
<button onclick="guessNum()"> Run Guess Num Function </button>
</body>
var ranNum;
function genNum() {
var ranNum = Math.floor(Math.random() * 101);
document.getElementById("demo").innerHTML =
ranNum;
}
function outputnum() {
x = document.getElementById("form1");
userguess = x.elements["userGuess"].value;
}
function guessNum() {
if (ranNum == userguess) {
alert("You are 70");
} else if (ranNum < userguess) {
alert("Less than 70");
} else {
alert("More than 70");
}
}
</script>
</html>

When you declare a variable with var ranNum, this makes it local to the function containing the declaration. So genNum is assigning to a local variable, while guessNum is looking at the global variable.
Remove the var keyword from the assignment in genNum.

The Quick of It
Welcome to Stack Overflow Duckling70. And, furthermore, welcome to JavaScript!
Please see a working example of your code here at JSfiddle.
Short Lesson in Scope
JavaScript variable declaration is interesting because it is dynamic and hoisted. Let me show you an example to show how function 'closure' and scope interplay:
var num = 3;
function printThree() {
return num
}
printThree() // returns 3 bc it can access the num variable set on "global scope"
console.log(num) // returns 3 from global scope
function printFive() {
var num = 5; // this variable exists only within this function
return num;
}
printFive() // returns 5 because it references num from the scope of the function
console.log(num) // returns 3 because it does not have access to the scope within the function
Full HTML Solution
Lastly here is the summative solution code for your problem:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Steps</h1>
<ol>
<li>Click Random Number.</li>
<li>Enter your guess then click Submit.</li>
<li>Click Run Guess Num Function to see how close you got!</li>
</ol>
<button onclick="genNum()">Random Number</button>
<p id="demo"></p>
<form id="form1">
Guess:<input name="userGuess" type="number" size="20">
</form>
<button onclick="setOutputNum()">Submit</button>
<button onclick="compareGuessToNum()">Run Guess Num Function</button>
</body>
<script>
var ranNum;
var userGuess;
function genNum() {
ranNum = Math.floor(Math.random() * 101);
document.getElementById("demo").innerHTML = ranNum;
}
function setOutputNum() {
var x = document.getElementById("form1");
userGuess = x.elements["userGuess"].value;
// Set userGuess to number instead of string
userGuess = +userGuess
}
function compareGuessToNum() {
if (ranNum === userGuess) {
alert("You are 70");
} else if (ranNum < userGuess) {
alert("Less than 70");
} else {
alert("More than 70");
}
}
</script>
</html>
Further Reading
Eloquent JavaScript has a good explanation on scope.

Related

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.

Addition to a variable reaches condition border, yet conditionied behavior doesn't take place

The purpose of the following script is to count the number of tries a user answered wrong (filled in a wrong password as value). After the "tries" variable went from 0 to 2, the error variable becomes 1 and the user is moved out from the form's webpage.
I tried to use conditionals to establish a flow of that process but these seem to fail in the sense that wrong password won't get the user out of the site and the correct password isn't recognized.
I seem to have a logical mistake I might lack some knowledge to find for now and it feels sour.
As a beginner I ask, what's wrong in the conditional system?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
document.querySelector("#myButton").onclick = function() {
let tries = 0;
let error = 0;
let password = 'tiesto';
let passwordValue = document.querySelector("#user").value;
if (passwordValue === password) {
document.location = 'http://www.maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 2) {
error++;
}
if (error === 1) {
document.location = 'http://www.microsoft.com';
}
};
</script>
</body>
</html>
In the function you are intializing tries to 0, so it becomes 0 each time the function is called and after increment becomes 1, and it never reaches 2 you can declare tries outside the function, something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
document.querySelector("#myButton").onclick = function() {
let error = 0;
let password = 'tiesto';
let passwordValue = document.querySelector("#user").value;
if (passwordValue === password) {
document.location = 'http://www.maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 2) {
error++;
}
if (error === 1) {
document.location = 'http://www.microsoft.com';
}
};
</script>
</body>
</html>
You put let tries = 0; in the onclick funtion, so it will be set to 0 everytime, never reach 2, so just move it out of the function.
let tries = 0;
document.querySelector("#myButton").onclick = function() {
let error = 0;
let password = 'tiesto';
Thanks to Dij, and Evelyn Ma, I now understand my mistake.
I didn't realize invoking a function on an event (such as onload) necessites taking all variables set to 0 or a string out of the function so these won't be changed by function execution:
Each time the event is triggered and the function executed, the values will be resetted if declared inside the function so the level set in the condition will never be reached.
For example: When var tries set to 0 outside the function, the user could try up until, say, 3 tries and in each execution the var won't be resetted but if it's inside the function it will go back from 1 to 0 each try.
I also had 2 other unrelated mistakes in the code:
besides moving all variables set to 0 or a string outside, I had to include the querySelector inside to check it's value each time anew.
I didn't use return, and in a specific correct way.
Note: Passwords shouldn't be on the code but be called from Database, but this is just an exercise.
Here's the full working exercise code:
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
Enter password to continue: <br>
<input type="text" id="passwordInput"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordInput) {
return window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>

JS | Receiving NaN as output when trying to pull content from text input

I'm new to JS and having trouble parseing text input into a calculation function. I must be doing something fundamentally wrong as I know the actual parse method is correct. I've been trying a bunch of different things but am kind of running around in circles at this point. I'm just making a simple celius/farenheit converter. Any help is greatly appreciated!
NOTE I'm trying to use pure JS only
<body>
<h2>Temperature Converter</h2>
<form>
<input id="degrees" type="text" size="5">
<input type="radio" value="celsius" name="one" id="celsius">Celsius
<input type="radio" value="farenheit" name="one" id="farenheit">Farenheit
<button id="equals" type="button">=</button>
<output id="output">
</form>
<script type="text/javascript" src="js/script2.js"></script>
</body>
var val = parseFloat(document.querySelector("#degrees").value);
var output = document.getElementById("output");
window.addEventListener("load", main);
function main() {
// listen for a click on the "equals" button
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
}
function convert(val) {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
function toCelsius(val) {
output.value = (val - 32) / 1.8;
console.log(output.value);
}
function toFarenheit(val) {
output.value = val * 1.8 + 32;
console.log(output.value);
}
At this point
convert("val");
you give your convert() function the strings "val" to be used for conversion and not the variable. This leads to the NaN value in the computation later on.
You should move the line, where you retrieve the value val to inside the convert() function, so it will get updated upon the click. Currently you read the value just at startup (where it will most probably be empty) and never update it.
function convert() {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
var val = parseFloat(document.querySelector("#degrees").value);
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
Here is error
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
Nedd
document.querySelector("#equals").addEventListener(
"click", function(){convert(val);});
Yip the first commenter to your answer was on the nose. You need to update your val variable on click. You can declare it up top and then update it in the function call, or just create it as a scoped variable in the click listener.
Working fiddle: https://jsfiddle.net/6s5nx7dn/

HTML Javascript converter program

I am trying to create a simple HTML program that will allow the user to input a number or word, then if the userInput matches what I have defined, it changes that input to something else, then outputs the new value on the screen.
Also looking for a button to reset the program (at any time to start over)
Any ideas?
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test() {
var userInput = document.getElementById("userInput").value;
//Need to add If, else if, else to change the value of userInput
// for example, If xxxx value, set to yyyy, then output yyyy
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Working better now with... but where does the reset go? How do I format the output? all noob questions yes
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Convert the function to the following.
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
// I forgot the updating part here.
document.getElementById("otherIdToWriteOutput").innerHTML = "yyyy";
}
}
You can also add the reset button. And remove the current text using
document.getElementById("id").innerHTML = ""; // remove the inner html.

How do I get my javascript var to return in an html paragraph?

I'm writing a simple function just for fun for a friend, but my js function wont return x the way I want it.
I have a text field and a button. If a user inputs "no good lyer" x should return "Big Fucking Surprise!"
If a user inputs anything else with text, x should return "Leave her ass anyway!"
If a user doesn't input anything x should return "Make a decision!"
Here is my code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a decision about your ex.</p>
<p id="choice">Here is your Decision</p>
<form>
My Ex:<input type="text" name="myEx">
</form>
<button onclick="myLife()">Decide</button>
<script>
function myLife()
{
var x="";
if("myEx".text=="no good lyer")
{
x="Big Fu**ing Surprise!";
}
if("myEx".text!="no good lyer")
{
x="Leave her a** anyway!";
}
if("myEx".text=="")
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>
</body>
</html>
Sorry but javascript strings don't have methods called text. your trying to get the value of the input <input type="text" name="myEx"> with 'myEx'.text, which is strange to say the least but you need to use normal people javascript. try getElementsByName('myEx')[0]
Add this variable to the top of your function myLife:
var myEx = document.getElementsByName('myEx')[0].value
change every line like this:
"myEx".text
to simply this
myEx
First of all you should use === and !== operator to check for conditions, Try the code below
To get a value from a input text use .value
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a decision about your ex.</p>
<p id="choice">Here is your Decision</p>
<form>
My Ex:<input type="text" id="myText" value="">
</form>
<button onclick="myLife()">Decide</button>
<script>
function myLife()
{
var myText = document.getElementById("myText");
var x="";
if(myText.value==="no good lyer")
{
x="Big surprise!";
}
if(myText.value!=="no good lyer")
{
x="Leave her!";
}
if(myText.value === "")
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>
</body>
</html>
change your script to following
<script>
function myLife()
{
var x="";
if("myEx".text=="no good lyer")
{
x="Big Fu**ing Surprise!";
}
if("myEx".text!="no good lyer")
{
x="Leave her a** anyway!";
}
if("myEx".text==null)
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>

Categories

Resources