JS. How do you add input type " number" as a number _ and avoid strings? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

JS. How do you add input type " number" as a number _ and avoid strings?

HTML || JS - Is there a way to add inputs (specifically _ "number").value? If I had 3 input type = "number", How do you add their values as a number? When I did it, it added it up as a string. And when I used += it adds a number to the one input. Here's the code I had: https://code.sololearn.com/WYnILBeR2Kkx/?ref=app

19th Jul 2019, 3:54 AM
Ginfio
Ginfio - avatar
9 Answers
+ 2
Getting NaN as the output IS wrong. The first thing: Turning an HTML element into a number will result in NaN, you should probably get the value of it. Second: you don't have to use other lines to make them numbers: +document.getElementById("inp1").value (Notice that the plus sign is there, so you don't have to use seperate lines) Second: Now that I actually look at your code, I think it would be easier to use 2 - signs: inbA.value -- inpB.value Subtraction doesn't work on strings, so they will be treated as numbers, and you don't have to change lots of things
19th Jul 2019, 4:32 AM
Airree
Airree - avatar
+ 1
There are two different ways to turn a string into a number: with a plus sign and with parseInt. I personally like + better, since it js shorter and also accepts floats input = +input; input = parseInt(input);
19th Jul 2019, 4:10 AM
Airree
Airree - avatar
+ 1
I just showed you
19th Jul 2019, 4:15 AM
Airree
Airree - avatar
+ 1
Probably because you took the inputs while the page loaded; most people have problems typing that fast. Just use what you used at first: inpA = document.getElementById("inp1"); ... but.innerHTML = inpA.value - - inpB.value
19th Jul 2019, 4:51 AM
Airree
Airree - avatar
0
Airree Could u please show me on the code using +
19th Jul 2019, 4:15 AM
Ginfio
Ginfio - avatar
0
In addition to Airre: var input = parseInt(input, 10); Where 10 is specified radix. Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
19th Jul 2019, 4:20 AM
FedorT
FedorT - avatar
0
Airree , can u please look at my attempt code; im trying to add up the two inputs' .value and put it in the button.innerHTML. I tried + and i got NaN - not that i'm saying it's wrong, but can u show me the right way (in the code) Thanks _
19th Jul 2019, 4:25 AM
Ginfio
Ginfio - avatar
0
Airree , why is it giving me 0, even though i entered 5 and 9?
19th Jul 2019, 4:46 AM
Ginfio
Ginfio - avatar
0
Airree , it works _ Thanks ✔️💡
19th Jul 2019, 5:17 AM
Ginfio
Ginfio - avatar