简体   繁体   中英

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!

You can just do:-

var selected_id = this.id;

where this refers to the current element being referred to.

您可以像这样ui.item.id它: ui.item.id

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM