【发布时间】:2019-11-14 22:55:09
【问题描述】:
我正在尝试创建自定义 JQUERY 自动完成搜索,以便用户可以按标签或国家/地区进行搜索。如果他们键入一个国家/地区,则该国家/地区内的所有标签都应显示。我正在尝试复制 this 搜索。经过大约 2 天的尝试,我要求提供任何提示。这是我到目前为止的代码。
function addautcomplete() {
data= [
{label:"A",country:"Ar"},
{label:"B",country:"Ar"},
{label:"C",country:"Ar"},
{label:"1",country:"Br"},
{label:"2",country:"Br"},
{label:"3",country:"Br"}];
$.widget("custom.combobox", $.ui.autocomplete, {
_select: function(event, ui ) {
$( "#search" ).val( item.country );
$( "#search" ).val( item.label );
},
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function (ul, items) {
var that = this, currentCategory = "";
ul.append("<li' class='search_country_title'> Type your selection"+ "</li> ");
$.each(items, function (index, item) {
console.log(item);
if (item.country != currentCategory) {
ul.append("<li id='selected_geography2' value=" +item.reg_id+ ">" + item.country + "</li> ");
currentCategory = item.country;
}
that._renderItemData(ul, item);
//li = that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var t = "<p><span'>" + item.label+"</span>"+"</p>" ;
return $("<li></li>")
.data("item.autocomplete", item.label)
.append("<a id='selected_geography3' value='" +item.reg_id+ "'>" + t + "</a>")
.appendTo(ul);
};
$("#search").combobox({
minLength: 0,
source: data,
focus: function( event, ui ) {
$( "#search" ).val( ui.item.label );
return false;
}
});
};
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
<html lang="en">
<head>
</head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function() {
addautcomplete();
});
</script>
<body id='Mybody'>
<input id='search'> </input>
</body>
</html>
谢谢,
【问题讨论】:
-
能否请您提供一个完整示例来说明您尝试过的操作。 HTML、库..等
-
提供了工作示例。
-
您提供的链接使用了一个名为 select2 的插件。您可以在此处查看示例:select2.org/dropdown。你想使用它,还是仍然想要 jQuery UI?
-
非常感谢!我正在使用插件,无需重新发明轮子。
-
那我就把评论改成答案了。
标签: jquery autocomplete jquery-ui-autocomplete