2012-10-09 62 views
14

我有几个使用jQuery自动完成功能进行增强的输入字段。如何在选择事件触发时获取相应的输入字段?如何获取触发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 
    } 
}); 

回答

8

尝试使用$(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

谢谢,这就是它!我试图$(this).name想知道为什么它是未定义的。 :) –

+0

不客气,只是对此遗憾。 – Adil

1

使用$(this)

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

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

然后你可以使用$(this).prop('name')event.target.name得到名字。

demo

+0

+1对于event.target。对使用$(this)(闭包等)持怀疑态度。但工作和event.target是我的新信息。 – Awemo

3

至于我可以告诉在这个例子中,你就不需要$()this工作得很好,因为name是一个定义的属性。

this.name

23

我使用的匿名函数为source PARAM,和$(this)里面引用的funcion,而不是被触发它的元素。我不得不使用$(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

thx为此...我的也在源条款 – PeterG

+0

谢谢这就是我所需要的。当您想将自动填充输入字段的属性作为参数传递给目标查找脚本时,该功能特别有用。 –

+0

查询的值实际驻留在'request.term'中。至少我一直在用这个。 – silkfire

相关问题