hellomello
hellomello

Reputation: 8587

adding a number to a numerical string with jquery

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

Upvotes: 1

Views: 10446

Answers (3)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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

counter++ -> Assign and Increment

++counter -> Increment and Assign

Check this jsFiddle Code for proof

Upvotes: 4

George Ariton
George Ariton

Reputation: 41

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

Upvotes: -1

Zang MingJie
Zang MingJie

Reputation: 5275

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);

Upvotes: 8

Related Questions