Thomaszter
Thomaszter

Reputation: 1474

Trying to number objects in jQuery

I'm trying to number objects, which can be added to a cart with drag'n'drop. So, this snippet should check the current number written in span.amountVal, and easily add ´+1´ to this number, but the result is always ´1´. When I uncomment the ´alert(i++);´, the snippet work like I want to. I'm confused, what is this about?

$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
    var i = $(this).find("span.amountVal").text();

    // alert(i++);

    $(this).find("span.amountVal").text(i++);
});

Thank you.

Upvotes: 0

Views: 68

Answers (3)

What are you guys doing? It SHOULDN'T read a SPAN's value, it's bad practice. Instead, it should read the items length (inside an object, for example) and then display it.

Upvotes: 0

Alex
Alex

Reputation: 35407

you have a pre-increment/post-increment issue, the following change should solve it:

$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
    var i = $(this).find("span.amountVal").text();

    $(this).find("span.amountVal").text(++i);
});

Pre-Increment adds one to i and then returns i while Post-Increment adds 1 to i after it has been returned.

Below is a similar post on StackOverflow touching on the topic:

post increment vs pre increment - Javascript Optimization

Upvotes: 2

JJJ
JJJ

Reputation: 33143

i++ first returns the value of i, then increments it. When you have the alert( i++ ) in place, the variable is already once incremented.

Put the ++ in front of the variable:

$(this).find("span.amountVal").text( ++i );

Or simply add one to it since you're discarding the variable right after:

$(this).find("span.amountVal").text( i + 1 );

Upvotes: 2

Related Questions