2012-07-07 22 views
4

是否有可能使JQuery自動完成工作而不使用傳統的ID,標籤,值?JQuery自動完成不使用標籤,值,ID

舉例來說,我不希望使用:

[ { "id": "Botaurus stellaris", "label": "Great Bittern", "value": "Great Bittern" }, 
{ "id": "Asio flammeus", "label": "Short-eared Owl", "value": "Short-eared Owl" }] 

而是:

[ { "my_id": "Botaurus stellaris", "first_name": "Great Bittern", "last_name": "Great Bittern" }, 
{ "my_id": "Asio flammeus", "first_name": "Short-eared Owl", "last_name": "Short-eared Owl" }] 

於是想,什麼JQuery autocomplete一般需要id,value,label,我可以把它拿my_id, first_name, last_name,讓jQuery的自動完成對待如同id,label,value

當我不希望修改來自數據源的數據鍵時,在JQuery Autocomplete上顯示它時,這可能會很有用。

回答

2

沒關係,

發現從jQueryUI的的自動完成功能的示例源回答:

$("#city").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       url: "http://ws.geonames.org/searchJSON", 
       dataType: "jsonp", 
       data: { 
        featureClass: "P", 
        style: "full", 
        maxRows: 12, 
        name_startsWith: request.term 
       }, 
       success: function(data) { 
        response($.map(data.geonames, function(item) { 
         return { 
          label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, 
          value: item.name 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 2 
    }); 

這裏,source被分配了一個功能,即可以轉換和返回任何類型的鍵所需轉換爲JQuery的自動完成的id,value,label

可能會有所幫助。

1

還有更好的解決方案。它甚至記錄在jquery-ui網站上。

http://jqueryui.com/demos/autocomplete/#custom-data

$("input").autocomplete({..}) 
.data("autocomplete")._renderItem = function(ul, item) {return $("<li></li>") 
    .data("item.autocomplete", item) 
      .append("<a>" + item.label + "<br>" + item.desc + "</a>") 
      .appendTo(ul); 
    };