2011-10-16 50 views
3

我想設置Jquery UI插件只從字符串的開頭搜索。我發現一些類似的問題,但沒有可用的答案。 我有此代碼:jQuery UI自動完成 - 從字符串開頭搜索

$.ajax({ 
     url: "{!$basePath}/mesta.xml", 
     dataType: "xml", 
     success: function(xmlResponse) { 
      var data = $("city", xmlResponse).map(function() { 
       return { 
        value: $("name", this).text(), 
        id: $("name", this).text() 
       }; 
      }).get(); 
      $(".autocomplete").autocomplete({ 
       source: data, 
       minLength: 0 
      }); 
     } 
    }); 

謝謝。

+0

這是你在找什麼? http://stackoverflow.com/questions/2382497/jquery-autocomplete-plug-in-search-configuration – Samich

+1

或者這個? http://stackoverflow.com/questions/5791379/jquery-autocomplete-ui-search-at-beginning – Samich

+0

我知道這些主題,但我不知道何以將其複製到我的代碼。 – Darkry

回答

4

就申請什麼是鏈接@Samich發佈到您的source選項:

source: function(req, response) { 
    var re = $.ui.autocomplete.escapeRegex(req.term); 
    var matcher = new RegExp("^" + re, "i"); 
    response($.grep(data, function(item){ 
     return matcher.test(item.value); })); 
}, 

這裏是一個小提琴演示:http://jsfiddle.net/jensbits/PekQZ/