views:

14742

answers:

2

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?

+23  A: 

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());
Diodeus
Be careful of parseInt(), it recognizes "010" as 9 (values leading with a zero are parsed as octal).
MightyE
Bleh, "010" parses as 8 (not 8)
MightyE
+4  A: 

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1
Chuck