2

I'd like to know how to keep adding number to a varible. For instance the number starts at 0 then every time you click the button it adds 20. So the first click would change the variable to 20 then the next click 40. This is as far as I can get..

var n = 0;
$('#button).live('click', function() {
    newval = n+20;
    $('.number').append($('<p/>', {text: newval}));     
});

2 Answers 2

3

n never changes.
You need to replace your newVal variable with n.

Also, you missed a quote in your selector.

Sign up to request clarification or add additional context in comments.

Comments

1

You're adding 20, but not storing the result, here's what you're after:

var n = 0;
$('#button').live('click', function() {
    $('.number').append($('<p/>', {text: n += 20}));     
});​

You can see a demo of it here, using += you're adding 20 to n, and saving the result back to n, previously you were getting but never setting n, it was only setting newVal, which was thrown away.

2 Comments

Don't confuse him with side-effects.
@SLaks: Elaborate? It simplifies the example, not sure where the confusion would be.

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.