Javascript 如何在select2多选中预选值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26730167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:17:28  来源:igfitidea点击:

How to pre-select values in select2 multi select?

javascriptjqueryjquery-select2

提问by JavaTechnical

I am having a multiple select like this:

我有一个这样的多重选择:

<select multiple="multiple" class="myList">
        <option value="1" selected="selected">Apple</option>
        <option value="2" selected="selected">Mango</option>
        <option value="3" selected="selected">Orange</option>
</select>

Now, apart from those options which must come selected in the select box, I wanted additional ajax functionality which would give values from a remote source.

现在,除了那些必须在选择框中选择的选项之外,我还想要额外的 ajax 功能,它可以从远程源中提供值。

Here is my code for select2

这是我的 select2 代码

$(function(){
    $(".myList").each(function(){

                $(this).select2({
                placeholder: "Search for fruits",
                minimumInputLength: 2,
                multiple: true,
                id: function(e) { 
                return e.id+":"+e.name; },
                ajax: {
                    url: "https://localhost:8443/fruit_search",
                    dataType: 'json',
                    data: function(term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function(data, page) {
                    var frts=[];
                        $.each(data,function(idx,Frt){
                            frts[frts.length]=Frt;
                        });
                        return {
                            results: frts
                        };
                    }
                },
                initSelection: function(element, callback) {
                    var data = [];
                },
                formatResult: formatResult,
                formatSelection: formatSelection
                });
        });

});

But I am getting the error:

但我收到错误:

Error: Option 'id' is not allowed for Select2 when attached to a <select>element.

错误:当附加到<select>元素时,Select2 不允许使用选项“id” 。

But when I use <input type="hidden">then where should I keep the pre-selected options? How do I show them up when the select2 box appears?

但是当我使用时,我<input type="hidden">应该在哪里保留预先选择的选项?出现 select2 框时如何显示它们?

回答by Manjeet Singh Chauhan

If you only have values then you can use 'val'to get pre-selected values like this.

如果您只有值,那么您可以使用它'val'来获取这样的预选值。

var PRESELECTED_FRUITS = [ '1','2','3'];

$('.myList').select2({}).select2('val', PRESELECTED_FRUITS);  

回答by John S

You can use the "data" function to set the initial values:

您可以使用“数据”功能来设置初始值:

var PRESELECTED_FRUITS = [
    { id: '1', text: 'Apple' },
    { id: '2', text: 'Mango' },
    { id: '3', text: 'Orange' }
];

$('.myList').select2('data', PRESELECTED_FRUITS)

Note: The "val" function is another way to set the initial values, but you only specify the ids with that function. In that case you would have to supply an "initSelection" function that builds the objects from the ids.

注意:“val”函数是另一种设置初始值的方法,但您只能使用该函数指定 id。在这种情况下,您将不得不提供一个“initSelection”函数来从 id 构建对象。

Also note that the "id" option is not the only option that is forcing you to use a hidden input. You cannot use the "ajax" option with a select element either.

另请注意,“id”选项并不是强制您使用隐藏输入的唯一选项。您也不能将“ajax”选项与选择元素一起使用。

As for the "id" option, I don't think you need it. Just put logic in the ajax "results" function so it builds an array of objects that have the proper idand textproperties, or have the server return objects with those properties.

至于“id”选项,我认为你不需要它。只要把逻辑在Ajax“的结果”功能,所以它建立有合适的对象的数组idtext性质,或具有这些属性的服务器返回的对象。

jsfiddle demo

jsfiddle 演示

回答by Ferry Kranenburg

To preset values use the 'val' property to preset the selected values.

要预设值,请使用 'val' 属性来预设选定的值。

$(this).select2({
            val: ["1","2","3"]
    }

But why not remove the 'id' function? If possible you could return the correct 'id' from the server without the need of the id function.

但是为什么不删除“id”功能呢?如果可能,您可以在不需要 id 函数的情况下从服务器返回正确的“id”。

回答by Pinguin Pinguin

You can also load the values into the HTML:

您还可以将值加载到 HTML 中:

<select class="selector" multiple="multiple" >
    <option selected value="1">Apple</option>
    <option selected value="2">Mango</option>
    <option selected value="3">Orange</option>
</select>

And connect select2 to it:

并将 select2 连接到它:

$(".selector").select2({
    width: 'inherit',
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    placeholder: "Search for fruits",
    ajax: {
        delay: 1000,
        url: "/bla_foo",
        dataType: 'json',
        type: "GET",
    }
})

and select2 will prefill the form.

并且 select2 将预填表格。

回答by Manoj

$("#select2").select2('data', {id: '3', text: 'myText'});