如何在select2多选中预先选择值? [英] How to pre-select values in select2 multi select?

查看:572
本文介绍了如何在select2多选中预先选择值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的多重选择:

<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>

现在,除了必须在选择框中选择的那些选项外,我还想要额外的ajax功能会从远程来源给出值。

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.

这是我的select2代码

Here is my code for 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
                });
        });

});

但我收到错误:


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

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

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

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?

推荐答案

如果你只有值,那么你可以使用'val'获得这样的预选值。

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

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

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

这篇关于如何在select2多选中预先选择值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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