Select2: Set default selection when using ajax select

Created on 12 Oct 2012  路  4Comments  路  Source: select2/select2

Is it possible to set the default selection {id: ..., text: ...} or another structure when using the Ajax dropdown? Tried setting both the data: and val: in the select2 jquery call to initial values (the initial value and one data record that contains its id and other values). However this doesn't seem to work... The placeholder seems to be available for the no current selection, or should i use it instead?

Most helpful comment

use the initSelection method in your call to select2. For example:
$('#element').select2({
initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},
minimumInputLength: 3,
ajax: {
url: your_remote_url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term //search term
};
},
results: function (data, page) {
return {results: data, more: false};
}
}
});

All 4 comments

use the initSelection method in your call to select2. For example:
$('#element').select2({
initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},
minimumInputLength: 3,
ajax: {
url: your_remote_url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term //search term
};
},
results: function (data, page) {
return {results: data, more: false};
}
}
});

Thanks that worked perfect :+1:

@brentan Thanks, it works for me!

In my case,

initSelection: function(element, callback) {
    callback({id: 1, text: 'default selection with id 1' });
},

had to be

initSelection: function(element, callback) {
    return callback({id: 1, text: 'default selection with id 1' });
},
Was this page helpful?
0 / 5 - 0 ratings

Related issues

JuanWilde picture JuanWilde  路  3Comments

pbkracker picture pbkracker  路  3Comments

dnohr picture dnohr  路  3Comments

FezVrasta picture FezVrasta  路  3Comments

actricom picture actricom  路  3Comments