Select2:设置隐藏字段值 [英] Select2: set hidden field value
问题描述
我有以下代码:
<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
});
一切正常,直到我想为该字段设置一个现有值 - initSelection方法中的元素参数显示空值!
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');
它有效,但在select2的val方法中某处值消失了..
It works, but somewhere inside select2's val method the value dissapears..
我使用版本3.4.0的Select2与此更新 。
I use version 3.4.0 of Select2 with this update.
谢谢
推荐答案
以下是可行的解决方案:
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;
}
我不知道为什么,但是value参数不能是字符串 - 为了使它工作,它必须是一个字符串数组..否则select2将空值设置为输入字段。
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']);
证明 - http://jsfiddle.net/GZyeb/1/
这篇关于Select2:设置隐藏字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!