I want to get the content of a in html, it is a number. I want to have it in javascript so I can do calculations with it. The only problem is that it is returned as string. How can I get the content as a number?
Asked
Active
Viewed 1.3k times
0
-
**...** convert it to a number. – Kevin B Feb 13 '17 at 20:25
-
you can use `Number` Object like `Number("5") – Abhinav Galodha Feb 13 '17 at 20:32
1 Answers
2
You have to parse it as either an int or a float (depending on what this number represents).
var btn = document.getElementById("addBtn");
btn.addEventListener("click",function(){
var numberTxt = document.getElementById("number").value;
var number = parseInt(numberTxt,10);
console.log(number+1);
});
<label for="number">Number:</label>
<input type="text" id="number"/>
<input type="button" value="add 1 to number" id="addBtn"/>
For a thorough explanation about parseInt
please have a look here. Furthermore, regarding the parseFloat
, please have a look here. Reading both the references and thinking about what you want to do, you would pick either parseFloat
or parseInt
and you will make it.

Christos
- 53,228
- 8
- 76
- 108