2012-04-23 98 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