views:

57

answers:

3

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

A: 

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

var x = 0;
gmcalab
tried that, makes them all zero all the time
mcgrailm
Well you will have to define it as something I just put 0 because I don't know what value you are trying to derive. What are you basing the index off of, looks like `zincorp` has the right idea of what to base the index off of.
gmcalab
A: 
var x = $("#list>li").length + 1;
zincorp
that would be good but sometimes items get removed
mcgrailm
If the items get removed, this should still account for that as long as you are removing `<li>`'s
gmcalab
ok so lets say i have 4 li's x should be up to 3 then I add a fifth x goes to 4 i remove li3 and my x remains at 4
mcgrailm
+3  A: 

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>');
  };
})();
CMS
so then I call the the function by variable ? how are the parameters gonna make it into the function sorry never seen this done before
mcgrailm
just call `addLocation(options, location)`. The anonymous function with no parameters is there for the closure, the inner function that takes two parameters is what gets assigned to `addLocation`.
bcherry
that does did it thank you ! never would of thought of that
mcgrailm