Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
rball Avatar asked Jan 20 '09 05:01

rball


People also ask

How do you input an integer in JavaScript?

JavaScript parseInt() Function The parseInt() function is used to accept the string ,radix parameter and convert it into an integer.

How will you convert the string into integer value using JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

Does val () return a string?

val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.

How do I get just the value of an integer in jQuery?

Answer: Use the jQuery. isNumeric() method You can use the jQuery $. isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .


1 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.

like image 145
Diodeus - James MacFarlane Avatar answered Sep 21 '22 07:09

Diodeus - James MacFarlane