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
?
JavaScript (+) sign concatenates instead of giving sum? The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.
Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.
Basic JavaScript Addition The following code adds two numbers and stores the result in a variable named "sum": var x = 1; var y = 2; var result = x + y; The result is "3" in this simple example. Add numbers in JavaScript by placing a plus sign between them.
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
.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With