0

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.

3 Answers 3

2

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

the ++i thing did it, thank you. We will never learned out :)
2

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

Comments

0

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.

Comments

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.