0

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?

user7548524
  • 53
  • 1
  • 1
  • 6

1 Answers1

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