如何从select2下拉列表中删除用户输入的内容

问题描述 投票:0回答:1

我正在使用一个select2的jQuery插件,从远程服务器上进行ajax自动完成。但是用户输入的信息会被添加到下拉列表中。谁能帮帮我,如何在select2自动完成下拉列表中不显示用户输入?

这是我的js代码

$('#id_available_users').select2({
            placeholder: "Select an Existing User",
            allowClear: true,
            minimumInputLength: 3,
            tags: [],
            ajax: {
                url: '/api/users/',
                dataType: 'json',
                type: "GET",
                data: function (term) {
                    return {
                        query: term.term,
                    };
                },
                processResults: function (data) {
                if (data.length > 0)
                {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.name + ', ' + item.email + ', ' + item.location.city + ' ' + item.location.state + ' ' + item.location.zip + ' ' + item.location.country,
                            id: item.id,
                        }
                    })
                };
                }
                else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
            }
            },

        });

enter image description here

javascript jquery jquery-select2 jquery-events
1个回答
0
投票

终于,我想明白了。下面是我的解决方法。

$('#id_available_users').select2({
        placeholder: "Select an Existing User",
        allowClear: true,
        minimumInputLength: 3,
        tags: [],
        templateResult: function formatState (state) {
            if (!state.id) {
                return state.text
            }
            if (!state.text.name && !state.text.email) {
               return; // here I am excluding the user input
            }
            var $state = '<p><b>'+ state.text.name + '</b>, ' + state.text.email + ', ' + state.text.location.city + ' ' + state.text.location.state + ' ' + state.text.location.zip + ' ' + state.text.location.country +'</p>';
            return $state;
        },
        ajax: {
            url: '/api/users/',
            dataType: 'json',
            type: "GET",
            data: function (term) {
                return {
                    query: term.term,
                };
            },
            processResults: function (data) {
            if (data.length > 0)
            {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item,
                        id: item.id,
                    }
                })
            };
            }
            else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
        }
        },
    });

在这里,我已经改写了 模板结果 并设置一个检查,如果项目没有名称和电子邮件(这将是用户输入的),只需返回true,不要将其添加到下拉列表中。

© www.soinside.com 2019 - 2024. All rights reserved.