Javascript If ELSE involving user input - javascript

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>

Related

how to make calculator using javascript using on text box for input value and perform add and subtract using button

As below you can see I want perform calculation of adding and subtracting but the program not giving output of calculation. there is input box for operator 1 and operator 2. I create two function add and sub. And using document.getElementById I pass the value of a and b and want to calculate but the function is does not giving output.
<!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>
Operator1:<input type="text" id="a">
<br><br>
Operator2:<input type="text" id="b">
<br><br>
<input type="button" value="Add" id="add" onclick="addd()">
<input type="button" value="sub" id="sub" onclick="subb()">
<br><br>
Result: <input type="text" id="res">
<script>
function addd(){
var ra= document.getElementById('a').value;
var rb=document.getElementById('b').value;
var rab=ra+rb;
Document.getElementById('res').value==rab;
}
function subb(){
var ra= document.getElementById('a').value;
var rb=document.getElementById('b').value;
var rab=ra-rb;
document.getElementById('res').value==rab;
}
</script>
</body>
</html>
You want to make sure you're using the assignment operator, instead of the comparison operator.
Try document.getElementById('res').value = rab; instead.
I'll provide an example that you'll hopefully learn from, but I really recommend you go and learn the basics before you continue programming.
<!DOCTYPE html>
<html>
<head>
<style>input[type=number], button { display:inline-block; margin-bottom: 4px; }</style>
</head>
<body>
<input type="number" id="input-a">
<input type="number" id="input-b"><br>
<button type="button" id="add">Add</button>
<button type="button" id="subtract">Subtract</button><br>
<input type="number" id="result" disabled>
<script>
const resultElement = document.querySelector("#result");
const inputAElement = document.querySelector("#input-a");
const inputBElement = document.querySelector("#input-b");
document.querySelector("#add").addEventListener("click", event => {
resultElement.value = +inputAElement.value + +inputBElement.value;
});
document.querySelector("#subtract").addEventListener("click", event => {
resultElement.value = +inputAElement.value - +inputBElement.value;
});
</script>
</body>
</html>
The only thing that's not self-explanatory here is the actual calculation. Notice how I put a + at the start of each value +inputAElement.value? That's to cast the value to a number for the calculation. Otherwise in certain situations, the value could be treated as a text value and just mashed together (e.g. 5 + 1 = 51).
Use CSS styles to change the look, as shown in the style tag. Abusing won't make you any friends.
<!DOCTYPE html>
<html>
<head>
<style>input[type=number], button { display:inline-block; margin-bottom: 4px; }</style>
</head>
<body>
<input type="number" id="input-a">
<input type="number" id="input-b"><br>
<button type="button" id="add">Add</button>
<button type="button" id="subtract">Subtract</button><br>
<input type="number" id="result" disabled>
<script>
const resultElement = document.querySelector("#result");
const inputAElement = document.querySelector("#input-a");
const inputBElement = document.querySelector("#input-b");
document.querySelector("#add").addEventListener("click", event => {
resultElement.value = +inputAElement.value + +inputBElement.value;
});
document.querySelector("#subtract").addEventListener("click", event => {
resultElement.value = +inputAElement.value - +inputBElement.value;
});
</script>
</body>
</html>

Number Guessing game in 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 ("").

Generate random fact from an array [duplicate]

This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 2 years ago.
I was trying to make a random fact generator website which would generate some random facts from an array, This is how I expected it to work - First I created a button which on click would generate a random fact but unfortunately The button is not working. Please check the code below and tell me the mistakes that I made.
Code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
<script>
var facts = ["I will add more facts later" , 'Heaven']
var randomFact = randomlist(facts);
function generateFacts(){
getElementById('here').innerHTML = randomFact;
}
function randomlist(list){
var x = Math.floor(Math.random() * list.length);
return list[x];
}
</script>
</body>
</html>
There is no function called getElementById alone. You need to use the method inside document object. So, the function will be document.getElementById()
var facts = ["I will add more facts later", 'Heaven']
var randomFact = randomlist(facts);
function generateFacts() {
document.getElementById('here').innerHTML = randomFact;
}
function randomlist(list) {
var x = Math.floor(Math.random() * list.length);
return list[x];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
</body>
</html>
How about document.getElementById()?
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}
If you open the developer console you should see the error that points out the mistake:
The function getElementById is not defined.
So the function generateFacts should look like this:
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}
document is the owner of all the DOM elements of the page. So you should call it to help you find the element.

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>

Javascript. Why won't my string replace update show in my browser

I am trying to change the word "lion" to "monkey" by using a function by using .replace in Javascript. I have set a time interval on it and it does work, but only in the console. Not in the browser when I am viewing the page. Why? Do I need to assign/update/upload it to the HTML somehow?
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
}
setInterval(toggleCaps, 3000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="about">
<blockquote>
<p>
lion
</p>
</blockquote>
</div>
</body>
</html>
You need to update the html element with the replaced string as following:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
document.querySelector(".about").innerText = sum; //add this
console.log(sum);
}
setInterval(toggleCaps, 3000);
yes you need to update the html:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
document.querySelector(".about").innerText = sum;
}

Categories

Resources