0

Please help me with this issue:

There are an undetermined number of iterations in this set of code:

var c = 1;
for(c=1; c<x; c++){
    $('#'+l_id+'_'+c).on("keypress", function(f){
        com_guide_add_li((c+1), $(this).parent().parent().attr('id'), f);
    })
}

The problem, is that when the event is called, the (c+1) is the value of the last iteration + 1, not the value that it was somewhere during the iterations when this code ran.

How can I ensure that the original value of the (c+1) remains in the function call, ie that value that it was when the iterations to set the event call ran?

Thanks

*sorry for the long title

Yoshi
  • 54,081
  • 14
  • 89
  • 103
Dave
  • 1,356
  • 10
  • 15

1 Answers1

0

I think this should work, the early binding should take care of it.

var c = 1;
for(c=1; c<x; c++){¡   
     var tmp_var = c;        
     $('#'+l_id+'_'+c).on("keypress", function(f){                  
        com_gude_add_li((tmp_var+1), $(this).parent().parent().attr('id'), f);
    })
}

Let me know if that helps.

Option 2

Since you're using jquery, you can use the data method (more to read here):

var c = 1;
    for(c=1; c<x; c++){¡   
        $('#'+l_id+'_'+c).data("c", c);
        $('#'+l_id+'_'+c).on("keypress", function(f){            
            com_gude_add_li(($(this).data("c") + 1), $(this).parent().parent().attr('id'), f);
        })
    }
Deleteman
  • 8,500
  • 6
  • 25
  • 39
  • Option 1 won't work; `tmp_var` is in the same scope as `c`, so the only difference is that `tmp_var+1` ends up as `x` instead of `x+1`. – Neil Apr 18 '12 at 23:35
  • Many many thanks. Option 2 works like a charm. I would vote up your answer, but i don't yet have 15 rep :( – Dave Apr 19 '12 at 10:09
  • Don't worry about, glad to be of help :) – Deleteman Apr 19 '12 at 13:05