Peter Howe
Peter Howe

Reputation: 1403

How do I find the id of a jquery autocomplete input from within the onItemSelect callback?

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});
}

Upvotes: 0

Views: 7452

Answers (4)

Peter Howe
Peter Howe

Reputation: 1403

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

Upvotes: 1

Elzo Valugi
Elzo Valugi

Reputation: 27856

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.

Upvotes: 1

peirix
peirix

Reputation: 37741

Can't you specify the variable in the callback?

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

Upvotes: 0

Sneakyness
Sneakyness

Reputation: 5403

Wouldn't you just use $(this)?

Upvotes: 0

Related Questions