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

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


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


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


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

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

demo