2012-10-09 18 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

相關問題