+ 2
What's wrong with this code?
8 Antworten
+ 5
You only have to declare it once. When you have fetched a value from the user, that value will be stored in the variable until it is replaced or the program ends
+ 6
Correct.
Like so:
var a;
var b;
function myFunction() {
a = document.getElementById("in1").value;
b = document.getElementById("in2").value;
var y = parseInt(a)+parseInt(b);
document.getElementById("demo").innerHTML = y;
}
+ 5
Also if you use addition with two strings you will join the strings
Example:
var a = "The"
var b = "string"
var c = a + b
c would be "Thestring"
+ 4
Put
var a = document.getElementById("in1").value;
var b = document.getElementById("in2").value;
Inside the function myFunction
You may also want to convert the input from the user from a string to a number before the addition.
See:https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
So:
function myFunction() {
var a = document.getElementById("in1").value;
var b = document.getElementById("in2").value;
var y = parseInt(a)+parseInt(b);
document.getElementById("demo").innerHTML = y;
}
+ 3
I got it now, < Input > only take string as input so, I have to parse that string to a number for further use... otherwise it'll show error eg. NaN....
+ 3
jay If I want to use the value of a,b in other functions also then shouldn't I put them outside the function?
+ 3
I only declare variable once outside the function but have to fetch value again in every new function. Right??