使用select2自动标记粘贴字符串中的最后一项 [英] Auto tokenize last item in pasted string using select2

查看:86
本文介绍了使用select2自动标记粘贴字符串中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Select2创建允许自动标记化的输入.我已经使用以下选项初始化了select2输入:

I am using jQuery Select2 to create an input that allows auto tokenization. I've initialized the select2 input with the following options:

{
    tags: [''],
    tokenSeparators = [',', ' ']
}

非常基本的东西.当我在输入中键入文本字符串,然后输入逗号或空格时,完全按照我的期望对前一个字符串进行标记化.

Very basic stuff. When I type a string of text into the input, followed by a comma or space, the preceding string is tokenized, exactly as I would expect.

但是,我需要支持将文本粘贴到输入中.这是事情分崩离析的地方.

However, I need to support pasting of text into the input. This is where things fall apart.

如果我将'1、2、3、4'粘贴到输入中,则会得到1、2和3的单独标记,但是4没有标记.相反,它保留为input.select2-input的值,并且当焦点更改时,该值消失.

If I paste '1,2,3,4' into the input, I get separate tokens for 1, 2, and 3, but 4 is not tokenized. Instead, it remains as the value of the input.select2-input and when the focus changes the value disappears.

我尝试了许多不同的方法,但无济于事.

I have tried a number of different approaches, to no avail.

我尝试拦截粘贴事件,使用e.originalEvent.clipboardData.getData('text/plain')获取粘贴的字符串的值,取消该事件,并在字符串的末尾添加逗号,然后用超时的.select2('val', str)更改输入的值.

I have attempted intercepting the paste event, getting the pasted string's value with e.originalEvent.clipboardData.getData('text/plain'), cancelling the event, and adding a comma to the end of the string before changing the input's value with a timed out .select2('val', str).

我尝试在粘贴事件之后模拟逗号keypress事件. (.trigger({type: 'keypress', which: 188}))

I have tried simulating a comma keypress event after the paste event. (.trigger({type: 'keypress', which: 188}))

我尝试通过拆分粘贴字符串来更改数组中每个项目的input.select2-input值.

I have tried changing the value of input.select2-input for each item in the array created by splitting the paste string.

似乎没有任何作用.有什么想法吗?

Nothing seems to work. Any ideas?

推荐答案

基于,您可以使用以下适用于变体形式的代码:

Based on a question that you have posted, you can use the following code that works with the variations:

1 2 3 4

1 2 3 4

1,2,3,4

1,2 3,4

您可以检查 jsfiddle .请注意:我发现版本3.5.0的第三个版本有一个错误,因此您应该使用最新的3.5.1.

You can check this jsfiddle. Please note: I've found that version 3.5.0 has a bug with the third variation, so you should use the latest 3.5.1.

$("#select2-input").select2({
    tags: [''],
    tokenizer: function(input, selection, callback) {
        if (input.indexOf(',') < 0 && input.indexOf(' ') < 0)
            return;

        var parts = input.split(/,| /);
        for (var i = 0; i < parts.length; i++) {
            var part = parts[i];
            part = part.trim();

            callback({id:part,text:part});
        }
    }
});

这篇关于使用select2自动标记粘贴字符串中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆