How to force JS to do math instead of putting two strings together

Sean picture Sean · Jan 30, 2011 · Viewed 124.8k times · Source

I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?

var dots = document.getElementById("txt").value; // 5
function increase(){
    dots = dots + 5;
}

Output: 55

How can I force it to output 10?

Answer

Alex picture Alex · Jan 30, 2011

You have the line

dots = document.getElementById("txt").value;

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value, 10);

Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.