Tim
Tim

Reputation: 3131

Setting value in Select2 using javascript object as data source

I have a select2 initialized by following:

$('#bookingResource').select2({
    placeholder: "Select Resource",
    minimumInputLength: 0,
    multiple: true,
    allowClear: true,
    data: function() {
        return {results: sections };
    }
});

Sections is an object with the id and text keys used by select2.

I need to preselect a value using only the ID from another object.

$('#bookingResource').select2("val", object.resourceID);

I think I need to use the initSelection function, but I'm unsure how to formulate it so that I can return the text corresponding to the ID in the section object...

When I try and use the following initSelection example shown in the Select2 and call .select2("val"... I get no output at all.

initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    }

Upvotes: 0

Views: 1658

Answers (1)

ivan.sim
ivan.sim

Reputation: 9288

I think the docs of initSelection is rather unclear on this one. The key is to notice that initSelection

is supposed to process a value.

and

The function will only be called when there is initial input to be processed.

After some testing, I notice that initSelection is called either when:

  1. .select2('val', $preselect_non_empty_value) is called, or
  2. The corresponding HTML element has specified a non-empty value attribute.

Depending on how you retrieve your sections data, my fiddle may or may not answer your question. The first select2 calls .select2('val', 4) to set 4 to be the pre-selected ID of the object. The second select2 simply uses element.val() to pull the value from the HTML attribute.

Also, most examples on initSelection I have seen so far seems to expect the HTML element to contain some initial values. Otherwise, they do some AJAX thing. For example,

var id=$(element).val();
if (id!=="") {
    $.ajax($some_url, {
        //...
    }).done(function(data) { 
        callback(data); // data must be a single object
    });
}

Hope this helps.

Upvotes: 1

Related Questions