2012-04-23 90 views
2

我需要在自動完成的結果列表中添加另一個元素。這個元素不應該是可點擊的,並且應該充當搜索列表中的信息。jquery自動完成查詢

我想下面的代碼,並使用appendTo選項,但它似乎沒有工作

var acOptions = { 
    source: userNames, 
    minLength: 1, 
    appendTo: "<li class='ui-menu-item' role='menuitem'>Search by username </li>" 
}; 

$('input.userName').autocomplete(acOptions); 

有人能指導我在這裏?

+0

這是否提問/回答幫助呢? http://stackoverflow.com/q/8663189/497356 – 2012-04-23 12:18:02

回答

4

請問這是您要找的http://jqueryui.com/demos/autocomplete/#categories? 這是一個工作演示http://jsfiddle.net/pomeh/XJ47e/

HTML代碼

<div class="demo"> 
    <label for="search">Search: </label> 
    <input id="search" /> 
</div> 

<p>A categorized search result. Try typing "a" or "n".</p> 

Javascript代碼

$.widget("custom.catcomplete", $.ui.autocomplete, { 
    _renderMenu: function(ul, items) { 
     var self = this, 
      currentCategory = ""; 
     $.each(items, function(index, item) { 
      if (item.category != currentCategory) { 
       ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>"); 
       currentCategory = item.category; 
      } 
      self._renderItem(ul, item); 
     }); 
    } 
}); 


var data = [ 
    { label: "anders", category: ""}, 
    { label: "andreas", category: ""}, 
    { label: "antal", category: ""}, 
    { label: "annhhx10", category: "Products"}, 
    { label: "annk K12", category: "Products"}, 
    { label: "annttop C13", category: "Products"}, 
    { label: "anders andersson", category: "People"}, 
    { label: "andreas andersson", category: "People"}, 
    { label: "andreas johnson", category: "People"} 
]; 

$("#search").catcomplete({ 
    delay: 0, 
    source: data 
}); 

CSS代碼

.ui-autocomplete-category { 
    font-weight: bold; 
    padding: .2em .4em; 
    margin: .8em 0 .2em; 
    line-height: 1.5; 
}​ 
+0

感謝您的答案。這隻適用於我輸入一些關鍵字並且應該有一個匹配的字母。即使關鍵字與任何搜索參數不匹配,我仍然在尋找它仍然顯示爲幫助選項卡 – Vidya 2012-04-23 10:55:38

+0

您必須編輯上面的_renderMenu。目前它遍歷所有匹配的單詞,所以你只需要編輯它遍歷所有的單詞,然後顯示相關caterogies :) – pomeh 2012-04-23 11:00:43

+0

是的,但我不希望它是一個類別。如果沒有任何詞匹配,它應該會發生。它就像某種幫助標籤。 – Vidya 2012-04-23 11:40:11