views:

81

answers:

5

Hi,

i'm trying to add 1 to a value that I fetched from my HTML using jquery.

At the moment it is appending 1, treating the value as a string.

A: 
x = parseInt(x)+1 //assuming input in an integer

or

x = parseFloat(x)+1 //assuming input is non-integer

You need to force a type conversion to integer from string.

Diodeus
You should always specify the second argument of parseInt to avoid surprises.
Paolo Bergantino
+2  A: 

You want parseInt. You should provide a base argument, as Paolo mentions, for otherwise it may be interpreted as octal if it has a leading 0 (or hex, if it has a leading 0x).

js> parseInt("1", 10)+1
2
js> parseInt("010")
8
js> parseInt("0x10")
16
Brian Campbell
You should always specify the second argument of parseInt to avoid surprises.
Paolo Bergantino
@Paolo You're right, updated my answer to fix it
Brian Campbell
removed downvote. :)
Paolo Bergantino
+1  A: 

You can cast a string to number, using the Number function, it will work whenever the number is a integer or a float:

var i = Number(myValue) + 1;
CMS
+1  A: 

As requested (with jQuery)

$('.vote-count-post').each(function() {
  var n = parseInt($(this).text(), 10)+1;
  $(this).text(n);
});

This will add one to the element text. In this case, adds one to all votes on this page! (works in firebug - too bad it's only on the page)

altCognito
Hahaha, I just put that into a loop and ran it 1000 times. Funny results.
Paolo Bergantino
Highly entertaining first thing in the morning!
Jarret Hardie
+2  A: 

Be careful with parseInt! You should always specify the second argument, which is the base:

$('div.c2 a').text(
   parseInt($('div.c2 a').text(),10)+1
);
Paolo Bergantino