How to make the value of document.getElementById an integer variable, not a string?

I want to pass the value obtained from the html object, convert this value to an integer so that I can do arithmetic before outputting it. Since my code is standing now, it just adds them as a string. Thus, the value of 5 + modifier 100 ends up equal to = 5100, not 105.

Here is my form code:

<form> Add Amount: <select id="addTweets"> <option value=5>5</option> <option value=10>10</option> <option value=15>15</option> </select> </br> <input type="button" value="Add It" onclick="addTweet()" /> </form> 

Here is my script:

 function addTweet() { var mod = 100; var results = document.getElementById("addTweets").value; results += mod; document.getElementById("tweetsOutput").innerHTML = results; } 
+4
source share
6 answers

The unary plus ( + ) forces its operand to a number:

 var results = +document.getElementById("addTweets").value; ... typeof( results ); // number 
+13
source

You can use parseInt

 var results = parseInt(document.getElementById("addTweets").value); 
+2
source

Use parseInt:

 var results = document.getElementById("addTweets").value; var intResults = parseInt(results, 10) + mod; 
+2
source

just add parseInt, then you can add it usually

  var results = parseInt(document.getElementById("addTweets").value); 

EDIT:

parseInt alternate, you can use "| 0" using a bit or zero value

  var results = document.getElementById("addTweets").value|0; 
+1
source

Try:

 var valResult = document.getElementById("addTweets").value; // get the value of the field var results = parseInt(valResult) + mod; // convert the value to int to do calculation document.getElementById("addTweets").value = results; // assign results to the field value 
0
source

As a rule, you can convert the numeric values โ€‹โ€‹of strings to integers by performing a mathematical operation on it:

 x = "9"; //String numerical value y = 10;//integer value alert(x+y)// output 910; x = x*1; alert(x+y) // output 19 

Check out this demo.

0
source

All Articles