18th Oct 2018, 6:29 AM
Sin Cos Ø
Sin Cos Ø - avatar
8 ответов
+ 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
18th Oct 2018, 10:07 AM
jay
jay - avatar
+ 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; }
18th Oct 2018, 9:54 AM
jay
jay - avatar
+ 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"
18th Oct 2018, 7:35 AM
jay
jay - avatar
+ 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; }
18th Oct 2018, 6:54 AM
jay
jay - avatar
+ 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....
18th Oct 2018, 7:30 AM
Sin Cos Ø
Sin Cos Ø - avatar
+ 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?
18th Oct 2018, 8:07 AM
Sin Cos Ø
Sin Cos Ø - avatar
+ 3
I only declare variable once outside the function but have to fetch value again in every new function. Right??
18th Oct 2018, 9:57 AM
Sin Cos Ø
Sin Cos Ø - avatar