Ganbayar Gansukh
Ganbayar Gansukh

Reputation: 766

How to increment variable that is stored in variable with Javascript?

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

Upvotes: 0

Views: 1424

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

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++.

Upvotes: 0

Charlie
Charlie

Reputation: 23858

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

Upvotes: 1

Related Questions