如何将jQuery UI自动完成链接到几个输入元素?

我希望用户能够为n个Facebook好友添加分数。 我现在设置表单的方式有8个输入(我假设最多8个玩家)。 我有jQuery自动完成工作一个输入(以便用户可以添加Facebook的朋友),但我无法弄清楚如何以编程方式为所有8个输入分配自动完成。

更新:基于Mark的建议我按类选择,这允许我在播放器名称的所有文本输入上自动完成,但我仍然需要将值放在每个相关的隐藏输入中。 (对于每个自动完成的名称,都有相应的ID)

jQuery的:

 $(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 $( "
  • " ) .data("item.autocomplete", item) .append("" + item.label + "") .appendTo(ul); }; });

    HTML:

     




    您应该能够使用input [type = text],或为每个输入框分配一个类。

    轻微变化..

     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 $("
  • ").data("item.autocomplete", item).append("" + item.label + "").appendTo(ul); };

    它在jsfiddle上的例子 。

    然后在你的选择和焦点处理程序中使用$(this)来引用所选的输入框,并找到隐藏值,你可以使用$(this).next()假设下一个元素与玩家ID匹配。

    如果您不想为播放器ID使用类,则可以使用您为播放器名称设置的约定来查找如下所示的ID:

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