How to get the input element triggering the jQuery autocomplete widget?

血红的双手。 提交于 2019-11-29 16:32:49

问题


I have several input fields that are enhanced with jQuery auto-complete functionality. How to get the corresponding input field when a select event is triggered?

<input name="1" value="">
<input name="2" value="">
<input name="3" value="">

$('input[type=text]').autocomplete({
    source: 'suggestions.php',
    select: function(event, ui) {
        // here I need the input element that have triggered the event
    }
});

回答1:


Try using $(this)

$('input[type=text]').autocomplete({
    source: 'suggestions.php',
    select: function(event, ui) {
        // here I need the input element that have triggered the event
        alert($(this).attr('name'));
    }
});



回答2:


I was using an anonymous function for the source param, and $(this) inside it referenced the funcion, not the element that was triggering it. I had to use $(this.element).

The final code ended similar to this (I simplified it for demo purposes):

$( ".regionsAutocomplete" ).autocomplete({
    source: function(request, response){

        //The next line is the important one for this example
        var input = this.element;
        $(input).css('color','red');

        var data = {'foo':'bar'};
        $.ajax({
            'url': ajaxurl,
            'data': data,
            'method': "POST",
            'dataType': "json",
            'success': function(data) {
                response(data);
            }
        });
    }
});



回答3:


You can use $(this) or event.target.

Then you can get the name using $(this).prop('name') or event.target.name.

demo




回答4:


As far as I can tell for this example, you wouldn't need the $(). this would work just fine since name is a defined attribute.

this.name




回答5:


Use $(this)

 select: function(event, ui) {
        $(this).attr('name');
    }


来源:https://stackoverflow.com/questions/12808854/how-to-get-the-input-element-triggering-the-jquery-autocomplete-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!