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

后端 未结 5 2032
温柔的废话
温柔的废话 2021-01-01 14:18

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?

<         


        
相关标签:
5条回答
  • 2021-01-01 15:13

    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

    0 讨论(0)
  • 2021-01-01 15:17

    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'));
        }
    });
    
    0 讨论(0)
  • 2021-01-01 15:19

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

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

    demo

    0 讨论(0)
  • 2021-01-01 15:23

    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);
                }
            });
        }
    });
    
    0 讨论(0)
  • 2021-01-01 15:24

    Use $(this)

     select: function(event, ui) {
            $(this).attr('name');
        }
    
    0 讨论(0)
提交回复
热议问题