How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:

<span id="replies">8</span>

Using jquery I'm trying to add a 1 to the value (8).

var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);

What's happening is it is appearing like:

81

then

811

not 9, which would be the correct answer. What am I doing wrong?


Solution 1:

parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.

var currentValue = parseInt($("#replies").text(),10);

The second paramter (radix) makes sure it is parsed as a decimal number.

Solution 2:

Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used

var currentValue = parseInt($("#replies").text(),10);