简体   繁体   中英

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

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/

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/

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