1
votes

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())
1
element.val() should still be in scope in the callback function, so you should just be able to pass it as a parameter, should you not?Reinstate Monica Cellio
And removing the () ? callback({id: element.val)opalenzuela
element.val() gives me id, and if i use only it in callback method i'll get "undefined" text as selected value.free2use
Try with $(element).select2('val', element.val());fonini
Tried. First of all i cannot call select2("val", value) without initSelection defined. I think its because i'm triggering event on this select to fulfill depend one also. And even if i remove trigger it doesn't work either.free2use

1 Answers

1
votes

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);
}