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

Viewed 267016

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?

11 Answers

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.

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

var newValue = parseInt(currentValue) + 1

In regards to the octal misinterpretation of .js - I just used this...

parseInt(parseFloat(nv))

and after testing with leading zeros, came back everytime with the correct representation.

hope this helps.

You can use parseInt() method to convert string to integer in javascript

You just change the code like this

$("replies").text(parseInt($("replies").text(),10) + 1);
Related