简体   繁体   English

在select2 3.5.2中使用initSelection进行自定义筛选

[英]Using initSelection in select2 3.5.2 for custom filtering

I have a text field which uses select2. 我有一个使用select2的文本字段。 Here is the initialization: 这是初始化:

        $("#foo").select2({
            createSearchChoice:function(term, data) { 
                if ($(data).filter(function() { 
                    return this.text.localeCompare(term)===0; 
                }).length===0) 
                {return {id:term, text:term};} 
            },
            initSelection : function (element, callback) {
                var data = {id: element.val(), text: element.val()};
                callback(data);
            },
            tags:[],
            tokenSeparators: [","], 
            data: [...data goes here...]
        }); 

In this field, the user is supposed to put in a number, or select items from a list. 在此字段中,用户应该输入一个数字,或从列表中选择项目。 If an item that the user puts in doesn't appear on the list, it ought be created as a simple tag (id and text identical). 如果用户放入的项目未显示在列表中,则应将其创建为简单标记(id和文本相同)。 This works. 这有效。

What doesn't work is when I set the value programmatically: 什么不起作用是我以编程方式设置值:

myvar.find('.placeholder lorem-ipsum').val(number).trigger("change");

The way it works now, is that when I set it to any value, it takes it without complaint, making a new simple tag. 它现在的工作方式是,当我将它设置为任何值时,它会毫无怨言地采用它,制作一个新的简单标记。 However, if I were to remove the initSelection parameter completely, it would ignore unknown values, and use known values as taken from the list (where tags are complex - id and text are different). 但是,如果我要完全删除initSelection参数,它将忽略未知值,并使用从列表中获取的已知值(其中标记是复杂的 - id和文本不同)。

How do I make it so that if the value I set to the field is found on the list, it will use the item, and otherwise make a simple tag? 如何使它如果在列表中找到我设置的字段的值,它将使用该项,否则制作一个简单的标记? The way it works now (simple tags only) is sort-of acceptable, but I'd prefer it worked ideally. 它现在的工作方式(仅限简单的标签)是可以接受的,但我更喜欢它理想的工作。

EDIT: I've made examples for how it works with and without the initSelection parameter. 编辑:我已经举例说明了如何使用和不使用initSelection参数。

http://jppk.byethost12.com/with.html http://jppk.byethost12.com/with.html

http://jppk.byethost12.com/without.html http://jppk.byethost12.com/without.html

In short, I want it to work like with.html when I push "Add New Item" and I want it to work like without.html when I push "Add Existing Item". 简而言之,当我按“添加新项目”时,我希望它像with.html一样工作,当我按“添加现有项目”时,我希望它像without.html一样工作。

Here is my best interpretation of what you want. 这是我对你想要的最好的解释。

JSFiddle 的jsfiddle

The trick is to append the element to the select field. 诀窍是将元素附加到选择字段。

 var array = ['foo', 'bar', 'baz'] $.each(array, function(key, value) { appendSelect(value); }); $("#foo").select2(); $('#submit').click(function() { var val = $('#name').val(); $('#name').val(''); array.push(val); appendSelect(val); }); function appendSelect(value) { $('#foo').append($("<option></option>").text(value)); } 
 <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.1/css/select2.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.1/js/select2.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <div class='container'> <select id='foo' multiple="multiple" class='form-control'></select> <label>Input</label> <input id='name' /> <button id='submit'>submit</button> </div> 

Much, much later, I found a solution that works right: 很久以后,我找到了一个正常的解决方案:

    initSelection : function (element, callback) {
        var eArr = element.val().split(",");
        var data = [];
        for (var i=0;i<eArr.length;i++) {
            for (var j=0;j<preExistingData.length;j++) {
                if (preExistingData[j]["id"] === eArr[i]) {
                    data.push(preExistingData[j]);
                    continue;
                }
            }
            data.push({id: eArr[i], text: eArr[i]});
        }
        callback(data);
    },

This not only checks if the value is among the pre-existing values (in which case it uses that item), but also if the value is a comma-separated list of values (in which case it properly encapsulates them as JS objects). 这不仅检查该值是否在预先存在的值之间(在这种情况下它使用该项),而且还检查该值是否为逗号分隔的值列表(在这种情况下,它将它们正确地封装为JS对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM