Number Guessing game in javascript - javascript

I am a beginner javascript programmer. I made a very simple javascript number guessing game between 1 and 10. But it is not working. Could anybody take a look at this code and tell me what is wrong in this code.
// getting the value of a textbox
let guess=document.getElementById('text').value;
let GuessNumber=3;
// creating a function to check whether the userinput and the variable is same on the click of a button.
document.getElementById("submit").onclick=()=>{
// if the user input and the number is same just display gift
if(guess==GuessNumber){
document.getElementById("P").innerHTML="Gift";
}
// if the user input is not a number display 'it should be a number'
else if(isNaN(guess)){
document.getElementById("P").innerHTML="It should be a number";
}
// if the user input is a number greater than 10 or less than 1 display 'it is a number between 1 and 10.
else if(guess>11||guess<0){
document.getElementById("P").innerHTML="It is a number between 1 and 10. Not beyond 10 or below"
}
// or if it is not same as the guess number display 'better luck next time'
else{
document.getElementById("P").innerHTML="Better luck next time";
}
}
The problem here is ,these else if statement and if statement is not working. No matter what the input is it is just displaying better luck next time. here the guessing number is 3 and whenever i enter 3 then also it is displaying better luck next time. If it is not a number, then also it is displaying like this. What is wrong here. Could anybody please help.
The html of this code is here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body align="center">
<h1>Number Guessing Game</h1>
<h2>Guess a number between 1 and 10</h2>
<h2>If your guess is correct we will give you a gift :)
</h2>
<input id="text" type="text" placeholder="Guess">
<br><br>
<button id="submit">submit</button><br><br>
<p id="P"></p>
<script src="index.js"></script>
</body>
</html>

Your code doesn't work because you store input value outside the event listener so the result will always empty, instead you can create a variable with input and into the event create a const with value
let GuessNumber = 3;
let guess = document.getElementById('text'); // <-- assign input
document.getElementById("submit").onclick = () => {
const value = guess.value; // <-- take value
if (value == GuessNumber) {
document.getElementById("P").innerHTML = "Gift";
} else if (isNaN(value)) {
document.getElementById("P").innerHTML = "It should be a number";
} else if (value > 11 || value < 0) {
document.getElementById("P").innerHTML = "It is a number between 1 and 10. Not beyond 10 or below"
} else {
document.getElementById("P").innerHTML = "Better luck next time";
}
}
<h1>Number Guessing Game</h1>
<h2>Guess a number between 1 and 10</h2>
<h2>If your guess is correct we will give you a gift :)
</h2>
<input id="text" type="text" placeholder="Guess">
<br><br>
<button id="submit">submit</button><br><br>
<p id="P"></p>

The only problem with your code was, that you declared the variable let guessNumber & let guess
outside of the onClick action check the code below rest other code seems to be working fine
// creating a function to check whether the userinput and the variable is same on the click of a button.
document.getElementById("submit").onclick=()=>{
// getting the value of a textbox
let guess=document.getElementById('text').value;
let GuessNumber=5;
// if the user input and the number is same just display gift
if(guess==GuessNumber){
document.getElementById("P").innerHTML="Gift";
}
// if the user input is not a number display 'it should be a number'
else if(isNaN(guess)){
document.getElementById("P").innerHTML="It should be a number";
}
// if the user input is a number greater than 10 or less than 1 display 'it is a number between 1 and 10.
else if(guess>11||guess<0){
document.getElementById("P").innerHTML="It is a number between 1 and 10. Not beyond 10 or below"
}
// or if it is not same as the guess number display 'better luck next time'
else{
document.getElementById("P").innerHTML="Better luck next time";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body align="center">
<h1>Number Guessing Game</h1>
<h2>Guess a number between 1 and 10</h2>
<h2>If your guess is correct we will give you a gift :)
</h2>
<input id="text" type="text" placeholder="Guess">
<br><br>
<button id="submit">submit</button><br><br>
<p id="P"></p>
<script src="index.js"></script>
</body>
</html>

You only needed to define the guess inside the onclick event. Why this happens. This is because in your code the guess already gets a empty value when you first load the page and this value doesnt change when you click the button. So you need to define this variable inside the onclick event for this to work
// getting the value of a textbox
let GuessNumber=3;
// creating a function to check whether the userinput and the variable is same on the click of a button.
document.getElementById("submit").onclick=()=>{
let guess=document.getElementById('text').value;
// if the user input and the number is same just display gift
if(guess==GuessNumber){
document.getElementById("P").innerHTML="Gift";
}
// if the user input is not a number display 'it should be a number'
else if(isNaN(guess)){
document.getElementById("P").innerHTML="It should be a number";
}
// if the user input is a number greater than 10 or less than 1 display 'it is a number between 1 and 10.
else if(guess>11||guess<0){
document.getElementById("P").innerHTML="It is a number between 1 and 10. Not beyond 10 or below"
}
// or if it is not same as the guess number display 'better luck next time'
else{
document.getElementById("P").innerHTML="Better luck next time";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body align="center">
<h1>Number Guessing Game</h1>
<h2>Guess a number between 1 and 10</h2>
<h2>If your guess is correct we will give you a gift :)
</h2>
<input id="text" type="text" placeholder="Guess">
<br><br>
<button id="submit">submit</button><br><br>
<p id="P"></p>
<script src="index.js"></script>
</body>
</html>

Think in order of execution of the statement prospective. By the time document.click() event is happened variable "guess" is already stored in memory with empty value as it is the first statement to execute by the js engine. So you are always checking GuessNumber (3) with guess ("").

Related

Javascript If ELSE involving user input

I have to write a program in Javascript where the program takes the value of two variables from the user and then if both the variables are non-zero, then they will concatenate and if only one of them is non-zero, then they will get added. I have tried a lot but I am still not getting the output desired. This is what I have done
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Enter 1st number<input type="number"id="demo1"></p>
<p>Enter 2nd number<input type="number"id="demo2"></p>
<p>To get your answer, please press the button</p>
<button onclick="function1()">Your_Result</button></p>
<p id="ans1"> If any one of the the numbers is 0, then your answer is: </p>
<p id="ans2"> If both of your numbers are non-zero, then your answer is: </p>
<script>
A=parseInt(document.getElementById("demo1").value);
B=parseInt(document.getElementById("demo2").value)
if (A && B) {
var sum=""+A+B
function function1() {
document.getElementById("ans2").innerHTML = sum;
}
}
else {
sum= A+B;
function function1() {
document.getElementById("ans1").innerHTML = sum;
}
}
</script>
</body>
</html>
The problem you have is that all forular inputs are transmitted as strings. which means you try to calculate with strings. of course this doesn't work. that's why you have to convert the strings into integers beforehand. You do this with the parseInt() function.
After the button click, the calculation and result should take place inside the function. But in your code, you are writing your function definition inside the if-else conditions which is wrong. Here's the working:
function function1() {
A = parseInt(document.getElementById("demo1").value);
B = parseInt(document.getElementById("demo2").value);
if (A && B) {
document.getElementById("ans2").innerHTML = "If both of your numbers are non-zero, then your answer is: " + A + B;
document.getElementById("ans1").innerHTML = "If any one of the the numbers is 0, then your answer is: ";
} else {
document.getElementById("ans1").innerHTML = "If any one of the the numbers is 0, then your answer is:" + (A + B);
document.getElementById("ans2").innerHTML = "If both of your numbers are non-zero, then your answer is: ";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Enter 1st number<input type="number" id="demo1"></p>
<p>Enter 2nd number<input type="number" id="demo2"></p>
<p>To get your answer, please press the button</p>
<button onclick="function1()">Your_Result</button></p>
<p id="ans1"> If any one of the the numbers is 0, then your answer is: </p>
<p id="ans2"> If both of your numbers are non-zero, then your answer is: </p>
</body>
</html>
You need to check it inside the function. As it will reevaluate the values from dom once the function begin.
function function1() {
let A = parseInt(document.getElementById("demo1").value);
let B = parseInt(document.getElementById("demo2").value)
document.getElementById("ans2").innerHTML = (A && B) ? A + B : '';
}
<p>Enter 1st number<input type="number" id="demo1"></p>
<p>Enter 2nd number<input type="number" id="demo2"></p>
<p>To get your answer, please press the button</p>
<button onclick="function1()">Your_Result</button></p>
<p id="ans1"> If any one of the the numbers is 0, then your answer is: </p>
<p id="ans2"> If both of your numbers are non-zero, then your answer is: </p>

Im new with call api , can someone help me with this . Call Api link shortener with javascript

So I have a mission is call api to this website : https://shrtco.de/ and using link shortener like them. But I don't know how to call it . Can someone explain how to call this or maybe help me , thank you guys so much
This is my HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<p>Enter a link</p>
<input type="text">
<button>Enter</button> <br>
<p>Short domain</p>
<input type="radio" id="domain1" name="fav_language" value="domain1">
<label for="html">shrtco.de</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">9qr.de</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">shiny.link</label>
<p>Link generated</p>
ZZZZZ
</div>
<script src="getAPI.js"></script>
</body>
</html>
Following the example from the interface documentation, I have programmed a minimal illustrative example here.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shortcode example</title>
</head>
<body>
<input type="text" name="url" id="url" value="" required>
<button id="submit" type="submit">shorten</button>
<p id="result"></p>
<script>
const button = document.querySelector('button');
const input = document.querySelector('input');
const result = document.getElementById('result');
const shorten = (event) => {
let value = input.value.trim();
while (result.firstChild) {
result.removeChild(result.firstChild);
}
if (!value.length) {
throw new Error('well! you have to type in something!');
}
let promise = fetch('https://api.shrtco.de/v2/shorten?url=' + value);
promise.then(response => {
if (response.status !== 201) {
console.log('Looks like there was a problem: ' + response.status);
return;
}
response.json().then(data => {
let link = document.createTextNode(data.result.full_short_link);
result.appendChild(link);
}).catch(error => {
console.log(error.message);
})
});
}
button.addEventListener('click', shorten, false);
</script>
</body>
</html>
What is happening in this example?
First there are three elements - an input element for typing in the url to shorten, a button element for submitting the data and a paragraph for displaying the results of the api call.
The submit button gets an javascript event listener, that handles click events. Everytime you click on that button, the input element will be checked, if something was typed in. If the value of the input element has a length, it will be send to the shortening service. For that reason we produce a promise with the javascript fetch api.
The call with the fetch api returns a javascript promise, which we check for the response status code. The api returns a 201 "Created" status code, that says everything is alright. The api needs a little time for the response, but then we can decode the json response and print out the shortened link in the result paragraph.
What you should do
Try to understand the given example. Please read the interface documentation to get informations about what could be returned in a success case and whats happening when the request fails? The javascript fetch api is elemental for that.
Try to transfer the given example to your application. If you encounter problems, explain these problems in detail and ask for a solution.

Is the problem the onclick method or the represenation of the html element as a object

I'm new to javascript and this has been driving me nuts for the last hour
Here's the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id ="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
<script src = scripts/game.js ></script>
</body>
</html>
And here's the javascript
const submitButton= document.getElementById('submit')
alert('hi')
submitButton.onClick = function submitGuess() {
alert('button is live')
}
For some reason the submitGuess function is not being executed at all (at least I'm not seeing the alert). I had a lot more javascript but I reduced it to find out why it wasn't working.
Any help is much appreciated
As pointed out in the comments, you can add the event handler in the JavaScript via EventTarget.addEventListener, rather than the inline HTML attribute. For example:
document.querySelector('#submit').addEventListener('click', event => {
console.log(`${event.target.id} was clicked`)
});
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
const submitButton = document.getElementById('submit')
this line get the value before the DOM fully loaded the solution is to define the const after the page load like this
window.onload = function(){
const submitButton = document.getElementById('submit')
alert('hi')
if(submitButton){
submitButton.addEventListener('click', function() {
alert("Clicked!");
});
}else{
alert("Something Wrong")
}
}

Max.math for this function - Homework

Create an html page, add 3 text boxes in which the user will input 3 numbers :a,b,c
Add a button that, on click, will calculate the maximum number of the three. The result will be displayed in an alert. The program should not crash if the user does not input one or two numbers.
Cases:
If no number is introduced then a message should be displayed asking the user to input at least on number.
If only one number of the three is introduced, that number is the maximum number.
If two numbers are introduced then it should be displayed the maximum of the two.
If three numbers are introduced then it should be displayed the maximum of the three.
I started like this:
function displaysubmit() {
var numarA = document.getElementById("numarA").value;
var numarB = document.getElementById("numarB").value;
var numarC = document.getElementById("numarC").value;
var numarAAsNumber = parseInt(numarA);
var numarBAsNumber = parseInt(numarB);
var numarCAsNumber = parseInt(numarC);
if (!isNaN(numarAAsNumber) && !isNaN(numarBAsNumber) && !isNaN(numarCAsNumber)) {
var Submit = Math.max(numarA, numarB, numarC);
alert(Submit);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercitiul2</title>
<script src="exercitiul2.js" type="text/javascript"></script>
</head>
<body>
<label>a</label>
<input type="text" id="numarA" />
<label>b</label>
<input type="text" id="numarB" />
<label>c</label>
<input type="text" id="numarC" />
<button id="submit">Submit</button>
</body>
</html>
I don't know how start to write in script. Please help me.
You did good just missing some basics;
1 - Wrap your inputs and submit button in form
2 - Add on-click function to button
3 - Pass event into function
4 - prevent form from submitting/reloading using that event
5 - You do not need to add parse int, you can make your inputs type="number" instead
6 - in if statement check if all 3 fields are empty then display message, if not calculate the submit
Example:
function displaysubmit(event) {
event.preventDefault();
var numarA = document.getElementById("numarA").value;
var numarB = document.getElementById("numarB").value;
var numarC = document.getElementById("numarC").value;
if (numarA === "" && numarB === "" && numarC === "") {
alert("Enter at least one number");
} else {
var Submit = Math.max(numarA, numarB, numarC);
alert(Submit);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercitiul2</title>
<script src="exercitiul2.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>a</label>
<input type="number" id="numarA" />
<label>b</label>
<input type="number" id="numarB" />
<label>c</label>
<input type="number" id="numarC" />
<button id="submit" onclick="displaysubmit(event)">Submit</button>
</form>
</body>
</html>
Hint:
Select the elements by
document.getElementById("numarA").innerHTML
When left blank, it'll be "", and if you put it in any if statement it will return false e.g.
if (document.getElementById("numarA").innerHTML) {
someFunction();
}
won't do anything.
Did you add the button click event?
do
<button id="submit" onclick="displaysubmit()">Submit</button>

Automatically add negative sign to user input (PLUNKER ATTACHED)

http://plnkr.co/edit/v53QDV8604OwGc6VdVYw?p=preview
I have a very basic doubt which i am not able to figure out how to solve it. If you see the input field 'negative'- i have to take negative values from user.
User might enter '-34.45' , '-455' and so on. But if user enters '56' and goes to next input field, i want the entered field to update as '-56'
So i need to check first if negative sign is not there and then only add a negative sign. Any suggestions ?>
<html>
</html>
Get the number, check if it is under zero, if not, subtract from zero. Assign it back.
https://jsfiddle.net/subterrane/pnrmxhsv/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway:400,300,600">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
</head>
<body>
<div class="container">
<div>
<label for="num">Negative</label>
<input type="text" placeholder="-52" id="num">
</div>
</div>
<script>
document.querySelector('#num').addEventListener('change', function(e) {
var num = e.target.value;
num = parseFloat(num, 10);
if(!isNaN(num) && num > 0) num = 0 - num;
e.target.value = num;
})
</script>
</body>
</html>
omg, i cant believe i will be able to answer my own question. it works perfectly fine for me. here is the code i tried and it worked well.
$scope.$watch(function ($scope) {
if ($scope.params.speed != undefined && $scope.params.speed > 0) {
$scope.params.speed = $scope.params.speed - (2 * $scope.params.speed );
};
})

Categories

Resources