Assigning a variable outside of a function in JavaScript - javascript

I'm new to JavaScript. I'm to trying to assign a value to a variable that was getting by input in HTML. But it gives me the actual input if I assign the variable inside of the function only. I was trying to build a simple calculator. I will be thankful to you if you can help me. Refer to the following code.
let num1 = document.getElementById("input");
let num2 = document.getElementById("input2");
function myFunction() {
document.getElementById("p").innerHTML = num1 + num2;
}
<input Id="input">
<input Id="input2">
<button onClick="myFunction()">
<span id="p"></span>

let num1 = document.getElementById("input");
let num2 = document.getElementById("input2");
function myFunction() {
document.getElementById("p").innerHTML = parseInt(num1.value) + parseInt(num2.value);
}
<input Id="input">
<input Id="input2">
<button onClick="myFunction()">Add Numbers</button>
<span id="p"></span>

<script>
function myFunction() {
const num1 = document.getElementById("input").value;
const num2 = document.getElementById("input2").value;
document.getElementById("p").innerHTML = parseInt(num1) + parseInt(num2);
}
</script>

try this
<hmtl>
<head><title>Document</title></head>
<body>
<input Id = "input">
<input Id = "input2" >
<button onClick= 'myFunction(document.getElementById("input").value,document.getElementById("input2").value)'>
<span id="p"></span>
<script>
function myFunction(n1, n2){
document.getElementById("p").innerHTML = parseInt(n1)+parseInt(n2);
}
</script>
</body>
</html>

Related

I wrote a function that sums the numbers I entered in the inputs, but it didn't work, why?

sorry if it's silly.I want to add the numbers I entered in two separate inputs, but it doesn't work.
<body>
<input type="number" id="number1"/>
<input type="number" id="number2"/>
<button onclick="plus()">Sum</button>
<script>
function plus (){
let numberbox1 = document.getElementById("number1");
let numberbox2 = document.getElementById("number2");
let newnumber = numberbox1 + numberbox2;
let div = document.get.createElement("div");
div.innerText = newnumber ;
document.body.appendChild(div);
}
</script>
let div = document.getElementById("num");
function plus (){
let numberbox1 = +document.getElementById("number1").value;
let numberbox2 = +document.getElementById("number2").value;
let newnumber = numberbox1 + numberbox2;
console.log(newnumber)
div.textContent = newnumber;
}
<input type="number" id="number1"/>
<input type="number" id="number2"/>
<button onclick="plus()">Sum</button>
<div id="num"> </div>

Adding two numbers in javascript from two inputs in a form

I am new in JavaScript. As a result I was practicing some codes that reads two numbers from a form and display the result on a button click. I also want to add a reset button to start a new calculation. The problem is the result field is not updating on button click but the reset button is working. Below is my code:
const btn = document.getElementById('btn');
const calc = document.getElementById('calc');
function add() {
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const result = document.getElementById('result');
if (num1 && num2 !== NaN) {
calc.addEventListener('click', () => {
let sum = num1 + num2;
result.value = sum;
return false;
});
} else {
alert("Enter Valid Number");
}
}
btn.addEventListener('click', () => {
num1.value = " ";
num2.value = " ";
result.value = " ";
});
<form id="adder" onsubmit="return add();">
<input type="text" name="num1" id='num1' placeholder="enter number">
<input type="text" name="num2" id='num2' placeholder="enter number">
<button id="calc" type="button">Add</button>
<input type="text" name="num3" id="result" readonly placeholder="Result">
<button type="button" id="btn">Clear</button>
</form>
You need to create addEventListener of calc button outside add(); and call add(); into event;
const btn = document.getElementById('btn');
const calc = document.getElementById('calc');
function add() {
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const result = document.getElementById('result');
if (num1 && num2 !== NaN) {
let sum = num1 + num2;
result.value = sum;
return false;
} else {
alert("Enter Valid Number");
}
}
calc.addEventListener('click', () => {
add();
});
btn.addEventListener('click', () => {
num1.value = " ";
num2.value = " ";
result.value = " ";
});
<form id="adder" onsubmit="return add();">
<input type="text" name="num1" id='num1' placeholder="enter number">
<input type="text" name="num2" id='num2' placeholder="enter number">
<button id="calc" type="button">Add</button>
<input type="text" name="num3" id="result" readonly placeholder="Result">
<button type="button" id="btn">Clear</button>
</form>
onsubmit doesn't fire because you didn't add a submit button, anyway that method doesn't work because you add an eventListener that will work after press submit.

Trying to implement a 5 function calculator in javascript using event listener

<html>
<head>
<title>JS Operator</title>
<script>
function calculate(num1, num2, op){
switch (op){
case '+' : return num1 + num2
case '-' : return num1 - num2
case '*' : return num1 * num2
case '/' : return num1 / num2
case '%' : return num1 % num2
}
}
</script>
</head>
<body>
<input id="num1" type="number" placeholder="Enter first number" name="num1"/> <br/><br/>
<input id="num2" type="number" placeholder="Enter second number" name="num2"/> <br/><br/>
<input id="op" type="text" placeholder="Enter operator" name="op"/> <br/><br/>
<button id="calculate" name="calculate"> Calculate </button><br/>
<p id="result">Result: </p>
<script>
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var op = document.getElementById("op").value;
document.getElementById("calculate").addEventListener("click", function(){
document.getElementById("result").innerHTML = "Result: "
document.getElementById("result").innerHTML+= calculate(num1, num2, op)
})
</script>
</body>
This is the code i've written, not sure where it is going wrong, but upon hitting the calculate button, the result reads undefined. I also tried using parseInt() for the 2 numeric values but that didn't work, although when i try to print the values of the 3 vars using alert() it gives the same value as input. Please help someone to get through where the error is.
Your code has two (common!) issues:
Please put the .value() calls inside the event listener!
Wrap the .value() calls in Number(...) so that addition is numeric addition and not string concatenation.
Here's one possible look for your script at the bottom portion of your code:
const num1Box = document.getElementById("num1");
const num2Box = document.getElementById("num2");
const opBox = document.getElementById("op");
const resultArea = document.getElementById("result");
document.getElementById("calculate").addEventListener("click", () => {
const x = Number(num1Box.value);
const y = Number(num2Box.value);
const op = opBox.value;
resultArea.innerHTML = `Result: ${calculate(x, y, op)}`;
});
As suggested by #Ray, the posted solution is clean and clear have a look at it, apart from that the working example of your code is,
document.getElementById("calculate").addEventListener("click", function() {
document.getElementById("result").innerHTML = "Result: ";
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var op = document.getElementById("op").value;
console.log(num1, num2);
document.getElementById("result").innerHTML += calculate(num1, num2, op)
})
function calculate(num1, num2, op) {
switch (op) {
case '+':
return num1 + num2
case '-':
return num1 - num2
case '*':
return num1 * num2
case '/':
return num1 / num2
case '%':
return num1 % num2
}
}
<html>
<head>
<title>JS Operator</title>
</head>
<body>
<input id="num1" type="number" placeholder="Enter first number" name="num1"/> <br/><br/>
<input id="num2" type="number" placeholder="Enter second number" name="num2"/> <br/><br/>
<input id="op" type="text" placeholder="Enter operator" name="op"/> <br/><br/>
<button id="calculate" name="calculate"> Calculate </button><br/>
<p id="result">Result: </p>
</body>
</html>
I also tried out the following code after posting the question, was engaged so couldn't update. Below it is:
<html>
<head>
<title>JS Operator</title>
<script>
function calculate(){
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var op = document.getElementById("op").value;
var result = 0;
switch (op){
case '+' : result = num1 + num2;
break;
case '-' : result = num1 - num2;
break;
case '*' : result = num1 * num2;
break;
case '/' : result = num1 / num2;
break;
case '%' : result = num1 % num2;
break;
}
document.getElementById("res").innerHTML = "Result: ";
document.getElementById("res").innerHTML += result;
}
</script>
</head>
<body>
<input id="num1" type="number" placeholder="Enter first number"/> <br/><br/>
<input id="num2" type="number" placeholder="Enter second number"/> <br/><br/>
<input id="op" type="text" placeholder="Enter operator"/> <br/><br/>
<button id="calc"> Calculate </button><br/>
<script>
document.getElementById("calc").addEventListener("click", function(){calculate()})
</script>
<p id="res">Result: </p>
</body>
</html>

unexpected value in my feet to meters converter with pure javascript

//I'm trying to get a result in meters out of an input in feet.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
//For any number I type I get 0 as answer.
var feetInput = document.getElementById("feet-input").value;
var result = document.getElementById("result");
var total;
function calculate(){
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
For any number I type get 0 as answer.
Because your var feetInput = document.getElementById("feet-input").value; is only executed once you need to fetch always latest value on function call as below
//var feetInput = document.getElementById("feet-input").value;//only executed once
var result = document.getElementById("result");
var total;
function calculate(){
var feetInput = document.getElementById("feet-input").value;
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
The only issue that you have is that the value from feet-input is ONLY read when the page is loaded.
You'll need to get the value of feet-input before you do the calculation.
Just add var feetInput = document.getElementById("feet-input").value; to the line immediately after function calculate(){
Codepen: https://codepen.io/DeathCamel57/pen/xPPGrp?editors=0010

The code not working. I cannot identify the issue

I was writing some code and for some reason that I am unaware of, whenever I click on the button, the function that it is assigned does not run. Does anybody know why? Thanks in advance.
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p").innerHTML;
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text = "Your number, "+number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text = "Your number, "+number+", is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input");
prime(number);
}
</script>
<p id="p"></p><br>
<form id="input">
Your Number: <input type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>
Try this
<button onclick="funcito()" value = "Got my number">Got my number</button>
There are a couple of other issues with that code, so you won't get the result you are looking for. Try this code:
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p");
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text.innerHTML = "Your number, "+ number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text.innerHTML = "Your number" + number + " is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input").value;
prime(number);
}
</script>
<p id="p"></p><br>
<form>
Your Number: <input id = "input" type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>
Because you write onclick="funcito" which is wrong write onclick="funcito()". instead.

Categories

Resources