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?
JavaScript parseInt() Function The parseInt() function is used to accept the string ,radix parameter and convert it into an integer.
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.
val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With