esreli
esreli

Reputation: 5061

jQuery autocomplete: How to obtain HTML item's "id" attribute?

jQuery is new to me, thanks for bearing with me.

I have some text inputs in HTML:

<input type="text" class="NameTextID" id="fn.1">
<input type="text" class="NameTextID" id="ln.1">
<input type="text" class="EmailAddressTextID" id="ea.1">

Two inputs are of class NameTextID and one is of class EmailAddressTextID. Notice each id is unique.

I then would like to leverage jQuery's autocomplete function on any DOM item with a class from above.

$(document).ready(function() {
    $(function() {
        $( ".NameTextID" ).autocomplete({
            source: recEngineNames,
            minLength: recMinCharCount,
            select: recEngine
        });
        $( ".EmailAddressTextID" ).autocomplete({
            source: recEngineEmails,
            minLength: recMinCharCount,
            select: recEngine,
        });
    });
});

Now, in the function recEngine:

var recEngine = function(event, ui) {
    var selected_value = ui.item.value
    var selected_id = ????
}

jQuery passes two parameters, how can I obtain the id if the ui item that activated the recEngine function?

Thanks in advance!

Upvotes: 1

Views: 159

Answers (3)

palaѕн
palaѕн

Reputation: 73906

You can just do:-

var selected_id = this.id;

where this refers to the current element being referred to.

Upvotes: 2

Kld
Kld

Reputation: 7068

First thing you can use multi selectors by separating by a comma ','.

Then to get the element where that fired the event you can use the key word this or event.target. To get its id you can use $(event.target).attr('id')

$(event.target).attr('id')

$(document).ready(function() {
    $(function() {
        $( ".NameTextID, .EmailAddressTextID" ).autocomplete({
            source: recEngineNames,
            minLength: recMinCharCount,
            select: recEngine
        });
    });
});

var recEngine = function(event, ui) {
    var selected_value = ui.item.value;
    var selected_id = $(event.target).attr('id');
}

Upvotes: 0

Daniel Stradowski
Daniel Stradowski

Reputation: 3484

You can acces it like this: ui.item.id

Upvotes: 0

Related Questions