How to get the input element triggering the jQuery

2019-02-08 04:13发布

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

5条回答
小情绪 Triste *
2楼-- · 2019-02-08 04:27

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楼-- · 2019-02-08 04:51

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

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

demo

查看更多
Viruses.
4楼-- · 2019-02-08 04:52

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'));
    }
});
查看更多
The star\"
5楼-- · 2019-02-08 04:52

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

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-08 04:52

Use $(this)

 select: function(event, ui) {
        $(this).attr('name');
    }
查看更多
登录 后发表回答