2011-03-01 46 views
0

我希望用戶能夠爲n個Facebook朋友添加分數。現在我有了我的表單,有8個輸入(我假設最多有8個玩家)。我有jQuery自動完成工作的一個輸入(以便用戶可以添加Facebook的朋友),但我不知道如何編程爲所有8個輸入分配自動完成。如何將jQuery UI自動完成連接到多個輸入元素?

更新:基於馬克的建議,我選擇的類,它允許我自動填充所有文本輸入的玩家名稱,但我仍然需要把值在每個相關的隱藏輸入。 (每一個自動完成的名字裏有一個對應的ID)

的jQuery:

<script type="text/javascript"> 
     $(function() { 
      var friends = {{friends}}; 
      $(".player-name").autocomplete({ 
       minLength:0, 
       source: friends, 
       focus: function(event, ui) { 
        $("this").val(ui.item.label); 
        return false; 
       }, 
       select: function(event, ui) { 
        $("this").val(ui.item.label); 
        //need to assign the appropriate value along with this name 
        $("#player-1-id").val(ui.item.value);     
        return false; 
       } 
      }) 
      .data("autocomplete")._renderItem = function(ul, item) { 
       return $("<li></li>") 
        .data("item.autocomplete", item) 
        .append("<a>" + item.label + "</a>") 
        .appendTo(ul); 
      }; 
     }); 
    </script> 

HTML:

<form name="input" id="game-log-form" action=""> 
<fieldset> 
<label>Player 1</label> 
<input type="text" id="player-1-name" class="player-name" value="" /> 
<input type="hidden" id="player-1-id" value="" /> 
<label>Score</label> 
<input type="text" size="6" id="points-1" /><br/> 
<label>Player 2</label> 
<input id="player-2-name" /> 
<input type="hidden" id="player-2-id" class="player-name" value="" /> 
<label>Score</label> 
<input type="text" size="6" id="points-2" /><br/>    
<label>Player 3</label> 
<input type="text" id="player-3-name" class="player-name" /> 
<input type="hidden" id="player-3-id" value="" />     
<label>Score</label> 
<input type="text" size="6" id="points-3"/><br/>      
<label>Player 4</label> 
<input type="text" id="player-4-name" class="player-name" /> 
<input type="hidden" id="player-4-id" value="" />     
<label>Score</label> 
<input type="text" size="6" id="points-4" /><br/>    
</fieldset>     
</form> 

回答

2

您應該能夠使用輸入[類型=文本],或分配每個輸入框都有一個類。

輕微變化..它上jsfiddle

var friends = [{id:1, "label": "jon", value:24}] 
$(".name").autocomplete({ 
    minLength: 0, 
    source: friends, 
    focus: function(event, ui) { 
     $(this).val(ui.item.label); 
     return false; 
    }, 
    select: function(event, ui) { 
     $(this).val(ui.item.label); 
     $(this).next(".playerId").val(ui.item.value); 
     return false; 
    } 
}).data("autocomplete")._renderItem = function(ul, item) { 
    return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul); 
}; 

實施例。

然後在您的選擇和重點處理程序使用$(this)參考選擇的輸入框,找到可以使用$(this).next()假設下一個元素匹配到玩家ID的潛在價值。

如果你不想使用一個類的玩家ID,你可以利用你在地方有約定的球員名字找到像下面的ID:

$("#" + $(this).attr("id").replace("-name", "-id")).val(ui.item.value); 
+0

意志,只有設置當前具有焦點的輸入的值? – 2011-03-01 00:44:31

+0

嘗試更新的答案。 。 。謝謝。 – 2011-03-01 00:55:32

+0

Closer(我爲所有輸入添加了一個類),但是這不會使id保持同步。所以我需要以編程方式確定。 – 2011-03-01 01:00:08