【问题标题】:Select2 - Tell if user entered in new search choice?Select2 - 判断用户是否输入了新的搜索选项?
【发布时间】:2014-03-09 17:49:31
【问题描述】:

我的 select2 选项如下所示:

$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-selecting 选项了吗?我不确定这是否是您需要的,但这是我在文档中看到的最接近的内容。
  • 另外,您可以在query 回调和createSearchChoice 回调中使用共享变量来跟踪何时是新选择,例如:pastebin.com/p63ZJcmR
  • 'select2-selecting' 正是我要找的!我不敢相信我错过了。添加您的评论作为答案,我会选择它。谢谢

标签: javascript ajax angularjs jquery-select2


【解决方案1】:

使用select2-selecting 事件,记录在此: http://ivaynberg.github.io/select2/#documentation

此外,您可以在查询回调和 createSearchChoice 回调中使用共享变量来跟踪何时是新选择,例如:

var newTerm = false;

$scope.select2Options = {
    query: function(query) {
        newTerm = false;
        ...
    },

    createSearchChoice: function (term, data) {
        term = $.trim(term);
        if (term) newTerm = term;
        ...
    }
};

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多