1

I have a counter and I'm trying to retrieve that number with jquery and add to it.

<div id='counter'>
32
</div>

So I'm trying to get the 32 with jquery and then add to it, +1.

var counter = $('#counter').text();
var counterPlus = counter++;

Is this supposed to work? It doesn't work for me

3 Answers 3

8

The type of counter is string, not number, so you need to convert it to number first:

var counterPlus = parseInt(counter, 10) + 1;

If you want to set it back:

$('#counter').text(parseInt($('#counter').text(), 10) + 1);
Sign up to request clarification or add additional context in comments.

2 Comments

@andrewliu it specifies the radix to use. This prevents unexpected behavior when the input contains leading zeroes. RTFD, as they say: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
Unnecessary. The counter++ expression works just fine. The issue is that OP is expecting incremented value to be returned, which is achieved by ++counter.
4

There is a basic different between counter++ and ++counter.

counter++ -> Assign and Increment

++counter -> Increment and Assign

Check this jsFiddle Code for proof

Comments

-1
var counter = parseInt(jQuery("#counter").text(), 10);
var counterPlus = counter++;

2 Comments

conversion wasn't the issue.. it was about counter++ and ++counter. See my jsFiddle jsfiddle.net/skram/me3Yu
counterPlus = counter++; //counterPlus = 32 counter = 33 <br /> counterPlus = ++counter; //counterPlus = 33 counter = 33 counterPlus = counter+1; //counterPlus = 33 counter = 32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.