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.
From stackoverflow
-
x = parseInt(x)+1 //assuming input in an integeror
x = parseFloat(x)+1 //assuming input is non-integerYou need to force a type conversion to integer from string.
Paolo Bergantino : You should always specify the second argument of parseInt to avoid surprises. -
You want
parseInt. You should provide a base argument, as Paolo mentions, for otherwise it may be interpreted as octal if it has a leading0(or hex, if it has a leading0x).js> parseInt("1", 10)+1 2 js> parseInt("010") 8 js> parseInt("0x10") 16Paolo Bergantino : You should always specify the second argument of parseInt to avoid surprises.Brian Campbell : @Paolo You're right, updated my answer to fix itPaolo Bergantino : removed downvote. :) -
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; -
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)
Paolo Bergantino : Hahaha, I just put that into a loop and ran it 1000 times. Funny results.Jarret Hardie : Highly entertaining first thing in the morning! -
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 );
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.