从json预选select2中的选项

时间:2014-04-16 09:58:31

标签: javascript jquery ajax json jquery-select2

与禁用一样:true和locked:true是否有办法预先选择select2中的选项? 我有一个文本字段,可以获取json数据,我想预先选择一个选项

有类似的东西吗?

{id: 0, text: 'story'},{id: 1, text: 'bug', selected: true},{id: 2, text: 'task'}

我知道可以使用initSelection完成,但我不明白如何选择:true

你能帮帮忙吗?

请看这里的代码:

http://jsfiddle.net/9PZTm/1/

2 个答案:

答案 0 :(得分:0)

我找到了适合我的东西

以下是有人需要的代码:

var items = [{id: 0, text: 'story'},{id: 1, text: 'bug', selected: true},{id: 2, text: 'task'}];
$(".form-control").select2({
    createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term, selected:term};} },
    multiple: false,
    data: items,
    width: 218,
    initSelection : function (element, callback) {
        $(items).each(function(){
           if (this.selected != undefined){
                callback(this);
           }
        });
    },
});

http://jsfiddle.net/9PZTm/2/

答案 1 :(得分:0)

我用数组代替

let arr = ['1','0']; 
$('#multiple').val(arr).select2();