views:

33

answers:

2

Hi, I'm using JQuery UI's autocomplete widget and would like to have access to the current selector which I'm attaching the autocomplete to. I have found a way to access the selector, using a previous question here, but the source function is called with incorrectly.

My current code looks like this

$("input[id$=artist]").each(function() {
    e1 = $(this);
    curID = $(this).parent('td').parent('tr').attr('id');       
    e1.autocomplete({
        minLength: 3,
        source: function(request, response) { 
            findSuggestions(request, response, 'artist', artist_cache, curID);
        }
    });
});

As you can see, I get the current selector and put it into e1. There are multiple rows with the given 'artist' input and I want to be able to know the ID for each row in the findSuggestions method but when the method is called, each row is given the same ID (which is the referencing the last of the rows.

Any idea why this might be occurring? Am I approaching this problem incorrectly?

Thanks!

+1  A: 

You need to define your variable inside the closure to give it local scope otherwise you are creating a global variable

$("input[id$=artist]").each(function() {
    var e1 = $(this);
    var curID = $(this).parent('td').parent('tr').attr('id');       
    e1.autocomplete({
        minLength: 3,
        source: function(request, response) { 
            findSuggestions(request, response, 'artist', artist_cache, curID);
        }
    });
});
redsquare
Ah, of course! Always a simple mistake, and always makes me feel dumb...thanks for the help!!
Conor B
+1  A: 

You forgot to put var before the curID variable.

That creates a global variable curID on the window object, so every source callback function is referring to the same object, and thus value.

Change to

var curID = $(this).parent('td').parent('tr').attr('id');       

Never forget to put var before a variable declaration, as it can be the source of painful bugs such as this one.

Anurag