views:

1772

answers:

4

I'm using the jquery autocomplete plugin from pengoworks: http://www.pengoworks.com/workshop/jquery/autocomplete_docs.txt

In the function called upon an entry being selected, I want to find out the name (id) of the input element. (Because the callback is going to be used for multiple autocompletes.)

Code looks like this:

myCallback = function(o) {
     // I want to refer to "myInput" here - but how?
}

setup = function() {
    $('#myInput').autocomplete('blah.php', {onItemSelect: myCallback});
}
A: 

Wouldn't you just use $(this)?

Sneakyness
No - $(this) is the autocomplete object. And the callback's argument is the chosen <li> element from the list of autocomplete suggestions. (I guess I could traverse the DOM from this LI element but that smacks of being a nasty hack that may not be future-proof.)
Peter Howe
What about giving that LI a unique ID?
Sneakyness
The LI's are generated by the autocomplete plugin (there's one for each suggestion in the autocomplete results) and don't have IDs - and I'm not aware of any facility to add them :-(
Peter Howe
A: 

Can't you specify the variable in the callback?

$('#myInput').autocomplete('blah.php', { onItemSelect: myCallback($(this)) });
peirix
+1  A: 

Try to pass the id of the in the extraParams to the server side:

$('#myInput').autocomplete('blah.php', {onItemSelect: myCallback}, extraParams: {name: $(this).attr('id')} );

or by adding some id to the blah.php?id=someid.

and then in the results array to send it back to the callback function.

Elzo Valugi
Yes - I thought of doing this - it just seems a bit nasty to have to involve the server in passing this info - when jquery has the element at the time of establishing and (probably) calling the callback. Thanks - this is a good alternative if no-one else has any ideas.
Peter Howe
+1  A: 
myCallback = function(li, $input) {
    // I need to refer to the appropriate "myXxxInput" here
    alert($input.attr('id'));
}

setup = function() {
    setupInput($('#myFirstInput'));
    setupInput($('#mySecondInput'));
}

function setupInput($input) {
    $input.autocomplete('blah.php', {onItemSelect: function(li) {
        myCallback(li, $input);} });
}

Thanks to Dylan Verheul (an author of the autocomplete) for this solution

Peter Howe
You're welcome :-)
dyve