如何获取触发jQuery自动完成小部件的输入元素?

21

我有几个输入字段,使用jQuery自动完成功能增强。当选择事件被触发时,如何获取相应的输入字段?

<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个回答

36

我曾经在source参数中使用匿名函数,然后在函数内部使用$(this)来引用该函数而不是触发它的元素。我必须使用$(this.element)来代替。

最终代码类似于这样 (为演示目的我简化了它):

$( ".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);
            }
        });
    }
});

1
谢谢,这正是我需要的。当您想将自动完成输入字段的属性作为参数传递到目标查找脚本时,它特别有用。 - Kosta Kontos
查询的值实际上驻留在request.term中。至少我一直都是这样用的。 - silkfire
好的支持,顺便问一下文档在哪里。 - Abbas

13

尝试使用 $(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'));
    }
});

谢谢,就这样了!我一直在尝试 $(this).name,想知道为什么它是未定义的。 :) - Nikola Obreshkov

4

您可以使用$(this)event.target

然后,您可以使用$(this).prop('name')event.target.name来获取名称。

演示


+1 针对 event.target。一开始有点怀疑使用 $(this)(闭包等),但两者都可以工作,而且 event.target 对我来说是新信息。 - Awemo

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

3
据我所知,对于这个例子,您不需要使用$()this 就可以正常工作,因为name是一个定义好的属性。 this.name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接