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 = 5
function increase(){
dots = dots + 5;
}
Outputs: 55
How can I force it to output 10
?
Could it possibly be an error in my script somewhere?
I'm initializing dots
like this:
dots = document.getElementById("txt").value;
the simplest:
the dots will be converted to number.
You have the line
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:
DON'T FORGET - Use
parseFloat();
if your dealing with decimals.This also works for you:
parseInt()
should do the trickGives you
http://www.w3schools.com/jsref/jsref_parseint.asp
UPDATED since this was last downvoted....
I only saw the portion
before, but it was later shown to me that the
txt
box feeds the variabledots
. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.One easy way to do this is to parse the textbox with an
onkeyup()
event to ensure it has numeric characters:where the event would give an error and clear the last character if the value is not a number:
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use
eval()
: