使用Aotocomplete,我想将名称(计数)显示为自动建议,当选择一个项目时,只在输入框中打印名称。我的数据格式是这样的
[{"name":"Test","count":"5"},{"name":"Javascript","count":"1"}]
可以显示名称而不计数的代码,打印多个选定项目:
jQuery(document).ready(function ($){
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$("#ctags-input")
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function(req, add){
var ctags_action = 'ctags_autosuggest';
$.getJSON(CTags.url+'?callback=?&action='+ctags_action, req, function(data) {
var suggestions = [];
$.each(data, function(i, val){
suggestions.push(val.name);
});
add(suggestions);
});
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
我试过suggestions.push(val)
;它不起作用。我也试过了
suggestions.push(val.name + "C" + count + ")" );
这可以显示名称(计数),但选中后,(计数)也会被选中。如何仅显示显示名称(计数)作为建议和输入名称?
答案 0 :(得分:0)
查看custom data and display demo。您可以将此示例与多个值代码结合使用,并显示计数以及项目的标签:
$("#ctags-input")
.bind( "keydown", function (event) {
/* snip */
})
.autocomplete({
source: function(req, add){
var ctags_action = 'ctags_autosuggest';
$.getJSON(CTags.url+'?callback=?&action='+ctags_action, req, function(data) {
var suggestions = [];
$.each (data, function(i, val) {
suggestions.push({
label: val.name,
count: val.count
});
});
add(suggestions);
});
},
/* snip */
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + " (" + item.count+ ")</a>")
.appendTo(ul);
};
示例: http://jsfiddle.net/NwRR6/(不包括远程部分)。