Simple example to set initial value of select2 element with Ajax source?

1.5k views Asked by At

I am trying to set the initial value of a Select2 element that is hooked up to an Ajax data source.

I am using v4 of Select2, and following the docs, which explain that initSelection has been replaced.

I have begun by trying to adapt the example in the "Loading remote data" section of the Select2 documentation. This is my code to set the initial value:

var $gitElement = $('.select2');
var option = new Option("yosssi/ejr", '29424443', true, true);
$gitElement.append(option);
$gitElement.trigger('change');

I end up with a tag showing undefined (undefined). What am I doing wrong?

JSFiddle here: http://jsfiddle.net/t4Ltcm0f/4/

1

There are 1 answers

0
odupont On BEST ANSWER

The error is is your templateResult and templateSelection functions. The 'repo' argument is an object not containing 'name' and 'full_name' properties, you should use the 'text' property instead.

function(repo) { 
    return repo.text || repo.name + ' (' + repo.full_name + ')';
}

Working JSFiddle here: http://jsfiddle.net/45891w6v/1/