How to force JS to do math instead of putting two strings together
the simplest:
dots = dots*1+5;
the dots will be converted to number.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
DON'T FORGET - Use parseFloat();
if your dealing with decimals.
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
.