Q:

Passing variable to jquery eq() function not working

For every tr I want to get the difference between one td containing a span with text and another td containing an input box on focussing out of the input in the 2nd td with the script below:
$(function() {
    var tr_no = $('.unitrows').length;
    for (i = 0; i < tr_no; i++) {
        $('.samples2issue input').eq(i).blur(function() {
            var diff = $('.samples_available span').eq(i).text() - $(this).val();
            alert(diff);
        })
    }
})​

Problem is substituting the variable i with a number say 0 in the var diff computation works.But using the i in itself returns a -ve value. Meaning $('.samples_available span').eq(i).text() returns 0. 
Could it be that since i is defined outside of the blur() function and it is not set   globally it is not picked when inside the blur() function.
Or how would I be able to replicate this using the each() function?
Thank you.

A:

The problem is that the code in the event handler is using the variable i after the loop has completed, so it will be one more than the index for the last element.
Use a closure to capture the value for the variable in each iteration:
for (var i = 0; i < tr_no; i++) {

  (function(i){

    $('.samples2issue input').eq(i).blur(function(){
      var diff = $('.samples_available span').eq(i).text() - $(this).val();
      alert(diff);
    });

  })(i);

}

