How to set selected value of jquery select2?

后端 未结 28 1353
野趣味
野趣味 2020-11-30 00:00

This belong to codes prior to select2 version 4

I have a simple code of select2 that get data from ajax



        
28条回答
  •  一生所求
    2020-11-30 00:36

    To build ontop of @tomloprod's answer. By the odd chance that you are using x-editable, and have a select2(v4) field and have multiple items you need to pre-select. You can use the following piece of code:

    $("#select2field").on("shown", function(e, editable){
        $(["test1", "test2", "test3", "test4"]).each(function(k, v){
            // Create a DOM Option and pre-select by default~
            var newOption = new Option(v.text, v.id, true, true);
            // Append it to the select
            $(editable.input.$input).append(newOption).trigger('change');
         });
    });
    

    and here it is in action:

    var data = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 2,
        text: 'duplicate'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
    ];
    
    $("#select2field").editable({
            type: "select2",
            url: './',
            name: 'select2field',
            savenochange: true,
            send: 'always',
            mode: 'inline',
            source: data,
            value: "bug, wontfix",
            tpl: '
                            
        
    提交评论

提交回复
热议问题