2012-02-08 7 views
2

jQuery-uiのオートコンプリートをページ内の複数の要素にバインドします。異なる分野のオプションの同じセット。何かのように:jQuery-ui/auto-complete/getJSON - 要素のIDを外部PHPに渡す方法

<input class='myclass' id='myid1' name='field1' type='text' /> 
<input class='myclass' id='myid2' name='field2' type='text' /> 
<input class='myclass' id='myid3' name='field3' type='text' /> 

私はjqueryの-UIオートコンプリートから「複数のリモート」オプションを使用していますので、Javascriptを次のようになります。

$(".myclass") 
    // don't navigate away from the field on tab when selecting an item 
     // don't navigate away from the field on tab when selecting an item 
     .bind("keydown", function(event) { 
      if (event.keyCode === $.ui.keyCode.TAB && 
       $(this).data("autocomplete").menu.active) { 
       event.preventDefault(); 
      } 
     }) 
     .autocomplete({ 
      source: function(request, response) { 
       $.getJSON("search.php" 
         ,{ term:extractLast(request.term) } 
         ,response); 
      }, 
      search: function() { 
       // custom minLength 
       var term = extractLast(this.value); 
       if (term.length < 1) { 
        return false; 
       } 
      }, 
      focus: function() { 
       // prevent value inserted on focus 
       return false; 
      }, 
      select: function(event, ui) { 
       var terms = split(this.value); 
       // remove the current input 
       terms.pop(); 
       // add the selected item 
       terms.push(ui.item.value); 
       // add placeholder to get the comma-and-space at the end 
       terms.push(""); 
       this.value = terms.join(", "); 
       return false; 
      } 
     }); 

それはすべてが非常に素晴らしい作品。 しかし、私はidを第2引数としてgetJSONに渡したいと思います。どうすればこれを達成できますか?

私は$ .getJSONの文に2つ目のパラメータを追加する方法を知っているが、私は、イベントトリガの「ID」をつかむことができませんよ。私は$(this).attr( 'id')を試しましたが、は私にはを与えませんでした。助言がありますか?

ありがとうございました。

答えて

4

"source"コールバック内のthisは、INPUT要素ではなく、プラグインのインスタンスであることに注意してください。

INPUTへの参照は、実際には「要素」プロパティのプラグインインスタンスに保存されます。
はこのようにそれを実行してください:それは完璧に動作

source: function(request, response) { 
    var inputID = this.element.attr('id'); 
    $.getJSON("search.php" 
     ,{ term:extractLast(request.term), id: inputID } 
     ,response); 
}, 

DEMO

+0

。どうもありがとうございました –

関連する問題