JavaScript code does not work as expected - javascript

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.

Related

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.

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>

Javascript Code for pick random number game not working

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.

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>

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.

Categories

Resources