Javascript 如何在select2.js中仅忽略空格

Javascript 如何在select2.js中仅忽略空格,javascript,jquery,Javascript,Jquery,在输入框中,当我只键入空格时,它将被接受并显示为空白,带有十字图标。 请给我一个解决方案。如何处理它 我的代码: $("#userfrm #field_value").select2({ maximumInputLength: 20, tags:tags, maximumSelectionSize : 10, createSearchChoice:function(term, data) { if ($(data).filter(f

在输入框中,当我只键入空格时,它将被接受并显示为空白,带有十字图标。 请给我一个解决方案。如何处理它

我的代码:

$("#userfrm #field_value").select2({
        maximumInputLength: 20,
        tags:tags,
        maximumSelectionSize : 10,
        createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
        multiple: true,
    });

您可以通过收听
select2选择
事件来拒绝空输入:

$("#userfrm #field_value").select2({
    maximumInputLength: 20,
    tags: tags,
    maximumSelectionSize: 10,
    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: true,
})
.on('select2-selecting', function(e) {
    if (!$.trim(e.val)) {
        e.preventDefault();
    }
});

演示:请分享相关的html代码也。并共享JSFIDLE,这将有助于您查看此链接并找到带有“事件日志”的keyoword