javascript output doesn't show - javascript

I'm creating a simple program called guess a number. I'm having problem showing my output. So I don't know if i got the right formula.
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.Random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>

You had a syntax error when generating a random number.
It should be
Math.random();
But you have
Math.Random();
Here is the complete code:
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>
When developing Javascript, always have your browser's console turned on. It would have showed you this error. All browsers have consoles.

Your code is correct but you need to test the function with a fixed number to see if it works, then use Math.random(); (lowercase random()), in this case, I'm using 11 as the correct number..
function guess() {
var num = document.getElementById("number").value;
//var answer = Math.floor(Math.random() * 100 + 1);
var answer = 11;
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>

// --- use Math.random instead of Math.Random ------
`
<script>
function guess() {
var num = document.getElementById("number");
//alert(num);
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>

Related

While loop in JS slows down browser

I am writing on a code that should guess a number the user entered and return a paragraph with a string and the number of tries the script needed to get the number. Nothing too fancy. The problem is that as soon as I start the page on firefox, it basically crashes down and I don't know why.
Thanks for the help.
This is my code:
<input id="guess" placeholder="Your Number">
<button id="guessButton">Guess it!</button>
<br>
<div id="scriptOutput"></div>
<script>
var myNumber = document.getElementById("guess").value
var guess = false
var scriptGuess = Math.random()
scriptGuess = scriptGuess*6
scriptGuess = Math.floor(scriptGuess)
var guessCount = 1
document.getElementById("guessButton").onclick = function() {
while (guess == false) {
if (myNumber == scriptGuess) {
document.getElementById("scriptOutput").innerHTML = "<p>" + "I got it after" + guessCount + "times!" + "</p>";
guess = true;
}else {
guessCount ++;
}
}
}
</script>
</body>
You are defining scriptGuess before the while loop, thus, each time the while loop runs, scriptGuess isn't changing. This is creating an infinite loop.
Try adding the guess logic inside of the while loop. This way, a new scriptGuess value is initialized every instance of the while loop:
<body>
<input id="guess" placeholder="Your Number">
<button id="guessButton">Guess it!</button>
<br>
<div id="scriptOutput"></div>
<script>
var myNumber = document.getElementById("guess").value
var guess = false
var guessCount = 1
document.getElementById("guessButton").onclick = function () {
while (guess == false) {
var scriptGuess = Math.random()
scriptGuess = scriptGuess * 6
scriptGuess = Math.floor(scriptGuess)
if (myNumber == scriptGuess) {
document.getElementById("scriptOutput").innerHTML = "<p>" + "I got it after" + guessCount + "times!" + "</p>";
guess = true;
} else {
guessCount++;
}
}
}
</script>
</body>
However, I still think you are going to run into problems with time complexity. This is going to take a lot of time to guess a user's inputted number, especially without a pre determined range.

How to show message instead of alert in javascript calculator as follows:

I want to calculate values of x and y from textbox values and the values
should not be empty and not alphabetic. I have been able to do all these
so far. However i do not want the result to be in a pop up. I want the
result to be displayed as a text just under the buttons and it says 'Your
result is.. '.
I have seen on the net that they use document.getElementById but I
don't know how to use it.
<html>
<form>
1st Number : <input type="text" id="num1" /><br>
2nd Number: <input type="text" id="num2" /><br><br>
<button onclick="add(num1.value,num2.value)">Addition</button>
<script>
function add(x,y) {
if(x.length == 0 || y.length == 0){
alert("Numbers cannot be blank");
return;
}
if(isNaN(x) || isNaN(y)){
alert("Value entered is not numeric");
return;
}
var result = parseInt(x) + parseInt(y);
alert("Addition: " + result);
}
</script>
</body>
</html>
I want the result to be displayed as a text just under the buttons and it
says 'Your result is.. '
Please send me the codes if you are able to do it.
Simply create a div element after your button:
<div id="result"></div>
And update it with the sum result by replacing your alert code:
var result = parseInt(x, 10) + parseInt(y, 10);
document.getElementById('result').innerHTML = 'Your result is ' + result;
<body>
<div>1st Number : <input type="text" id="num1" /></div>
<div>2nd Number: <input type="text" id="num2" /></div>
<button onclick="add()">Addition</button>
<div id='result'></div>
<script>
function add() {
let x = document.getElementById('num1').value;
let y = document.getElementById('num2').value;
if(x.length == 0 || y.length == 0){
alert("Numbers cannot be blank");
document.getElementById('result').innerText = '';
return;
}
else if(isNaN(x) || isNaN(y)){
alert("Value entered is not numeric");
}
var result = Number(x) + Number(y);
document.getElementById('result').innerText = "Your result is: " + result;
}
</script>
</body>

issue with random number guess game. Does not show if answer is correct

Why is this not working. There are no errors in console and compiler does not show anything specific. Probably something wrong with the variable check?
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (input == number) {
alert("got it");
} else("noup not now");
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>
The input variable is not defined anywhere, and I think you missed an alert in the else("noup not now") statement.
Side note: you are confronting a String with a Number, in this case it behave as expected because of Js Coercion and the equality operator.
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (numberSelected == number) {
alert("got it");
} else {
alert("noup not now");
}
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>

Inserting a loop into a Javascript number guessing game

For an assignment, I need to make a JS number guessing game. It needs to include a loop to check the user's guess and a reset game button. My problem is getting the loop to work. I want the number of turns to start at 10. Each time the user makes an incorrect guess, their number of turns decreases by 1, and if they guess correctly, their number of turns is 0. If they push the "Start New Game" button, a new number should be generated and the number of turns should be reset to 10.
The loop doesn't specifically need to be a while loop, I just need one in the code for my assignment. Can anybody help me out?
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="guess" placeholder="Insert your guess" type="number">
<input name="requestInfo" onclick="getResults()" type="button" value="Confirm">
<p></p>
<textarea cols="50" name="results" readonly="true" rows="8"></textarea>
<p></p><input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
while (turns > 0) {
if (guess == num) {
turns = 0;
document.Input.results.value = "Congratulations, you won! The mystery number was " + num + ".";
} else if (guess < num) {
turns--;
document.Input.results.value = "Your guess was too low. Turns remaining: " + turns;
} else if (guess > num) {
turns--;
document.Input.results.value = "Your guess was too high. Turns remaining: " + turns;
}
}
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
document.Input.guess.value = "";
document.Input.results.value = "";
}
function getResults() {
checkNumber();
}
</script>
</body>
Alright, I guess since it is a college/HS assignment your professor is trying to teach you using prompt under a loop.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="requestInfo" onclick="getResults()" type="button" value="Start Guessing!">
<input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
while (turns > 0) {
guess=prompt("Tell me your guess.", "Your guess: ");
if (guess == num) {
turns = 0;
alert("Congratulations, you won! The mystery number was " + num + ".");
} else if (guess < num) {
turns--;
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
turns--;
alert("Your guess was too high. Turns remaining: " + turns);
}
}
if (turns==0)
alert ("You failed to guess sadly.");
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
}
function getResults() {
checkNumber();
}
</script>
I agree that the taks seems a bit weird - obviously, with a non-modal dialog, you will not need a loop.
One thing you could do is use the prompt method (example: window.prompt("sometext","defaultText");), which would then open a modal dialog to ask the user until the number of remaining guesses is zero, or until the guess was correct. That would work within the loop.
Here have a go with this one. Makes sure that the user enters a number.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it? Click button to start game.</p>
<button type="button" onclick="startNewGame()">Start New Game</button>
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns;
function checkNumber() {
while (turns > 0) {
var guess = prompt("Insert your guess");
if (!guess || isNaN(guess)) {
alert("Please enter a valid number");
continue;
}
if (guess == num) {
alert("Congratulations, you won! The mystery number was " + num + ".");
return;
} else {
turns--;
if (guess < num) {
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
alert("Your guess was too high. Turns remaining: " + turns);
}
}
}
if (turns == 0) {
alert("You have lost");
}
}
function startNewGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
checkNumber();
}
</script>
</body>

Javascript function checks user input but always posts "wrong"

I got a task in class today- im asking the user a simple math qustion, and if the he answers correctly alert with "Correct" will pop up, if not a "wrong" alert.
<body>
<h1 style="text-decoration:underline">Math test!</h1>
<p id="question"></p>
<script>
var firstnum = Math.floor((Math.random() * 10) + 1);
var secondnum = Math.floor((Math.random() * 10) + 1);
var trueanswer = firstnum * secondnum;
function setquestion() {
document.getElementById("question").innerHTML = firstnum + " * " + secondnum;
}
setquestion();
function checkuseranswer() {
var useranswer = document.getElementById("useranswer");
if (trueanswer == useranswer) {
alert("Correct!");
}
else {
alert("Wrong!");
}
}
</script>
<h2>Press submit to test yourself</h2>
<input type="text" id="useranswer" />
<input type="submit" id="submit" value="submit" onclick="checkuseranswer()" />
I think the problem is that var useranswer isn't being recieved correctly, but debugging didn't help at all. I also tried putting function checkuseranswer in the botton, but same result.
All help appreciated.
var useranswer = document.getElementById("useranswer");
You're comparing against the DOM element itself, not the value of the input.
var useranswer = document.getElementById("useranswer").value;
An element will never equal a number, no matter how much you wish it.

Categories