views:

37

answers:

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}));     
});
+1  A: 

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.

Nick Craver
Don't confuse him with side-effects.
SLaks
@SLaks: Elaborate? It simplifies the example, not sure where the confusion would be.
Nick Craver
thanks for explaining
Alex
+1  A: 

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

Also, you missed a quote in your selector.

SLaks
thank you thank you
Alex