简体   繁体   中英

Select2 set selected value by id only

So, i have search wtform, one field of which is represented with select2. It is loaded dependently on another select field through ajax. Loading step works ok. But, when i submited my form, and received it back with result data, i cannot set selected value back to select2 field because i have only id, and, as i understood, callback method of initSelection requires both id and text. Or, maybe i am doing something wrong.

Here is select field

$("#source").select2({
    placeholder: "Выберите источник",
    initSelection: function(element, callback){
        callback({id: element.val(), text:element.val()})
    },
    query: function(query){
        query.callback(source_data)
    }
})

And i want something like below. Data with such id already present in select2, the only question is how to get it selected.

callback({id: element.val())

This is how I was able to solve this issue:

//sample preloaded select data
var preload_data = [{id: '1', text:'<span id="user1">John</span>'},{id: '2', text:'<span id="user2">Tim</span>'}, {id: '3', text:'<span id="user3">George</span>'}]

//the initSelection method
initSelection : function (element, callback) {
    var data = [];

    var lookup = {};
    for (var i = 0, len = preload_data.length; i < len; i++) {
        lookup[preload_data[i].id] = preload_data[i];
    }
    $(element.val().split(",")).each(function() {
        data.push({id: this, text: lookup[this].text});
    });
    callback(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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