2011-02-28 22 views
1

我試圖讓jQuery自動完成工作。問題是我的json數組由屬性「name」和「id」組成。 jQuery期望「價值」和「標籤」。我想將「名稱」映射到「標籤」和「ID」到「值」。如何將json值映射到jQuery UI的預期「值」和「標籤」?

這裏是工作的例子,在我使用jQuery的期望屬性名稱:

$(function() { 
     var projects = [ 
      {value: "aaron-112", label: "Aaron"}, 
      {value: "andy-123", label: "Andy" }, 
      {value: "greg-122", label: "Greg" }]; 

     $("#project").autocomplete({ 
      minLength: 0, 
      source: projects, 
      focus: function(event, ui) { 
       $("#project").val(ui.item.label); 
       return false; 
      }, 
      select: function(event, ui) { 
       $("#project").val(ui.item.label); 
       $("#project-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> 

<div class="demo"> 
    <input id="project"/> 
    <input type="hidden" id="project-id"/> 
    </div> 

但我的JSON是這樣的:

[{id: "aaron-112", name: "Aaron"}, 
    {id: "andy-123", name: "Andy" }, 
    {id: "greg-122", name: "Greg" }]; 

回答

2

你能在使用前修改數據它與插件?

例如:

var newProjects = []; 
$.each(projects, function() { 
    newProjects.push({ value: this.id, label: this.name }); 
}); 

然後使用newProjects與插件?

+0

好答案,應該這樣做! – McHerbie 2011-02-28 21:25:42