我正在使用类别的JQuery自动完成功能,让用户从列表中选择一个项目。
我现在要做的是允许用户将新项目添加到两个可用类别中的一个。
这就是我现在所拥有的:
HTML:
<input id="procura"></input>
JS:
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this,
currentCategory = "";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
$(function () {
var data = [{
label: "Vendas",
category: "Recebimentos"
}, {
label: "Serviços",
category: "Recebimentos"
}, {
label: "Outros",
category: "Recebimentos"
}, {
label: "Fornecedores",
category: "Pagamentos"
}, {
label: "FSW",
category: "Pagamentos"
}, {
label: "Outros",
category: "Pagamentos"
}];
$("#procura").catcomplete({
delay: 0,
source: data
});
});
JSFiddle here
答案 0 :(得分:1)
您需要添加输入以收集要添加到下拉列表中的新项目,以及应添加它的类别。然后,只需将新项目推送到数据阵列。
以下代码已根据您提供的内容进行了扩展,但您需要添加该代码,以便用户可以选择一个类别:
HTML:
<input id="procura"></input>
<br>
New Item:
<input id="new_item"></input><button onclick="add_item();">Add</button>
JS:
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this,
currentCategory = "";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
var data = [{
label: "Vendas",
category: "Recebimentos"
}, {
label: "Serviços",
category: "Recebimentos"
}, {
label: "Outros",
category: "Recebimentos"
}, {
label: "Fornecedores",
category: "Pagamentos"
}, {
label: "FSW",
category: "Pagamentos"
}, {
label: "Outros",
category: "Pagamentos"
}];
function add_item()
{
var add_to_list = {};
add_to_list['label'] = $('#new_item').val();;
add_to_list['category'] = "Recebimentos"; // ADD INPUT TO CHOOSE
data.push(add_to_list);
$('#new_item').val('');
}
$(function () {
$("#procura").catcomplete({
delay: 0,
source: data
});
});
请在此处查看jsfiddle:http://jsfiddle.net/E9eWa/10/
这个答案也提供了类似的见解:Adding values to jQuery autocomplete real time