mcgrailm
mcgrailm

Reputation: 17640

javascript increment index in function

I'm just trying to figure out how to create an index inside a function so I can keep track of the items its generating and I'm not sure how to do this seems like I should know this..

addLocation(options,location)

   funciton addLocation(options,location){
       $('#list').append('<li class="location"><div>'+location.label+'</div>'+
        '<input type="hidden" name="location['+x+'][lat]" value="'+location.lat+'" />'+
        '<input type="hidden" name="location['+x+'][lon]" value="'+location.lon+'" />'+
        '<input type="hidden" name="location['+x+'][loc]" value="'+location.loc+'" />'+
        '<input type="hidden" name="location['+x+'][label]" value="'+location.label+'" />'+
    '</li>');
   }

now normally you have a forloop to help you keep track of things but int this instance I'm not appending items in a loop and I keep getting an error saying x in undefined

appreciate any help you can give

thanks Mike

Upvotes: 0

Views: 4542

Answers (3)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827496

Since what you want is that each time the function is called, x should be incremented, you can store x in a closure, for example:

var addLocation = (function (){
  var x = 0; // store x
  return function (options,location) {
    x++; // increment x
    $('#list').append('<li class="location"><div>'+location.label+'</div>'+
    '<input type="hidden" name="location['+x+'][lat]" value="'+location.lat+'" />'+
    '<input type="hidden" name="location['+x+'][lon]" value="'+location.lon+'" />'+
    '<input type="hidden" name="location['+x+'][loc]" value="'+location.loc+'" />'+
    '<input type="hidden" name="location['+x+'][label]" value="'+location.label+'" />'+
    '</li>');
  };
})();

Upvotes: 3

zincorp
zincorp

Reputation: 3282

var x = $("#list>li").length + 1;

Upvotes: 0

Gabe
Gabe

Reputation: 50493

Declare x since in your above code it's not defined.

var x = 0;

Upvotes: 0

Related Questions