I have the following code:
<input type="hidden" name="airport" tabindex="6" />
$('input[name="airport"]', '#details-form').select2({
minimumInputLength: 3,
multiple: true,
separator: ';',
width: 'off',
initSelection : function (element, callback) {
var data = [];
$(element.val().split(';')).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
url: History.getBasePageUrl() + 'get-airports-dictionary',
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
var code = parseInt(data[0]);
switch (code) {
case 0:
return {results: data[1]};
break;
default:
window.Common.showError(data[1]);
break;
}
}
},
formatResult: formatAirportResult,
formatSelection: formatAirportSelection
});
Everything works fine untill I want to set an existing value for that field - the element argument inside initSelection method shows empty value!
$('input[name="airport"]', '#details-form').select2('val', '2');
I tried to set the original value with the following code:
$('input[name="airport"]', '#details-form').val('2');
It works, but somewhere inside select2's val method the value dissapears..
I use version 3.4.0 of Select2 with this update.
Thank you
Here is the working solution:
$('input[name="airport"]', '#details-form').select2({
minimumInputLength: 3,
multiple: true,
separator: ';',
width: 'off',
initSelection : function (element, callback) {
var data = [];
$(element.val().split(',')).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
label: item[1]
});
});
callback(data);
},
ajax: {
url: History.getBasePageUrl() + 'get-airports-dictionary',
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
var code = parseInt(data[0]);
switch (code) {
case 0:
return {results: data[1]};
break;
default:
window.Common.showError(data[1]);
break;
}
}
},
formatResult: formatAirportResult,
formatSelection: formatAirportSelection
});
function formatAirportResult(item) {
return item.label + ' <strong class="pull-right">' + item.code + '</strong>';
}
function formatAirportSelection(item) {
return item.label;
}
I don't know why, but value argument can't be string - in order to make it work it has to be an array of strings.. Otherwise select2 sets empty value to input field.
$('input[name="airport"]', '#details-form').select2('val', ['2:Domodedovo', '3:Vnukovo']);
Proof - http://jsfiddle.net/GZyeb/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With