0

I have large block of html that is stored in a variable that contains a variable that should increment upon function.

Seems like this is very basic, yet couldn't figure out.

var x = 1,
    foo = '<p>This should count ' + x +'</p>';

$('#add').click(function () {
    $('#form-dynamic').append(form);
    x++;
});
7
  • 2
    Move foo inside the click handler. Commented Apr 29, 2016 at 14:49
  • 2
    Did you mean x instead of count and form instead of foo? Otherwise I can't make any connection. Commented Apr 29, 2016 at 14:54
  • @Bergi sorry, that was mistake. Commented Apr 29, 2016 at 14:55
  • The value of foo is a string. Even though you originally built it using the value of x, the string won't magically update if x changes. Think about this simplified example: var a = 1; var b = 2 + x;. At this point, b has the value 3. Would you expect that if I do a = 3, b will also somehow update to 5? Instead, whenever x changes have to "rebuild" foo. Commented Apr 29, 2016 at 15:00
  • :) yep, somehow I magically expected that. I completely forgot about the static variable. Commented Apr 29, 2016 at 15:01

2 Answers 2

1

For one thing, your variable x is NOT a variable stored in another variable. It is a normal JS variable. So, just change x the way you change any variable.

var x = 1;        

$('#add').click(function () {
    $('#form-dynamic').append(form);
    foo = '<p>This should count ' + x +'</p>';
    x++;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your variable is static. So at any point, it will show the same value. To get the latest value, each time you click, move it inside the event handler to re-execute and re-assign the latest value:

var x = 1, foo;
$(function () {
  $('#add').click(function () {
    foo = '<p>This should count ' + x +'</p>';
    $('#form-dynamic').append(form);
    x++;
  });
});

And also change the count++ to x++.

1 Comment

Yeah, it was meant to x++, somehow I wrote it here count++. Thank you for reminding me about static variables.

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.