Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  57] [ 1]  / answers: 1 / hits: 142531  / 14 Years ago, sun, january 30, 2011, 12:00:00

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?


More From » string

 Answers
6

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.


[#93990] Thursday, January 27, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dakotahs

Total Points: 605
Total Questions: 104
Total Answers: 113

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;