Javascript 选择2-告诉用户是否在新的搜索选项中输入?
右键“我的选择2”选项如下所示:Javascript 选择2-告诉用户是否在新的搜索选项中输入?,javascript,ajax,angularjs,jquery-select2,Javascript,Ajax,Angularjs,Jquery Select2,右键“我的选择2”选项如下所示: $scope.select2Options = { ajax: { dataType: 'json', url: '/api/locations/', data: function(term) { return { search: term }; }, results: function(data
$scope.select2Options = {
ajax: {
dataType: 'json',
url: '/api/locations/',
data: function(term) {
return {
search: term
};
},
results: function(data) {
var locations = data.locations.map(formatLocations);
return { results: locations };
}
},
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
}
};
如您所见,我使用的是angular-ui-select2指令,但是如果我使用的是普通的jquery-select2,我的选项将是相同的
代码允许用户添加搜索词,但我想知道是否有一种好方法可以告诉用户何时输入了新的搜索选项
现在我只能想到:
1) 等待用户从输入中模糊出来
2) 向我的服务器发出ajax调用,查看它是否包含输入的当前值
缺点是,即使用户正在选择一个现有的选项,我也总是这样做(2)
我希望有像“onNewSearchChoice”这样的活动我可以听
有人有什么建议吗?使用
select2 selection
事件,记录如下:
此外,您还可以在查询回调和createSearchChoice回调中使用共享变量来跟踪何时为新选项,例如:
var newTerm = false;
$scope.select2Options = {
query: function(query) {
newTerm = false;
...
},
createSearchChoice: function (term, data) {
term = $.trim(term);
if (term) newTerm = term;
...
}
};
您是否查看了
select2选择选项?我不确定这是否是您需要的,但这是我在文档中看到的最接近的东西。此外,您可以在查询
回调和createSearchChoice
回调中使用共享变量来跟踪何时是新的选择,例如:“select2 selecting”正是我要找的!真不敢相信我错过了。添加您的评论作为答案,我将选择它。谢谢