[英]Proper usage of jQuery select2's initSelection callback with remote data
我使用jQuery select2插件来使用提供的ajax回调函数检索邮政编码,如下所示:
$(document).ready(function() {
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 3,
ajax : {
url : "/bignibou/utils/findGeolocationPostcodeByPostcodeStartingWith.json",
dataType : 'json',
data : function(term) {
return {
postcode : term
};
},
results : function(data) {
console.log(data);
return {
results : $.map(data, function(item) {
return {
id : item.id,
text : item.postcode
};
})
};
}
}
});
});
一旦选择了两个邮政编码,我就会在DOM中得到hidden input
:
<input type="hidden" class="bigdrop select2-offscreen" id="postcodes" style="width:600px" name="familyAdvertisement.postcodes" value="4797,4798" tabindex="-1">
我遇到的问题是,一旦重新显示表单(例如,在某些其他控件出错的情况下),虽然hidden input
确实存在,但选择(即两个邮政编码,尤其是text
)不会在表单中显示有两个值(即4797和4798,这是邮政编码的id
)。
我不确定如果重新显示表单或者有更好的方法,我是否必须再做一次ajax往返。
任何人都可以建议吗?
initSelection方法必须传递必须存在于select2
例如:
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 1,
data:[],
initSelection : function (element, callback) {
var data = [{id:1,text:'bug'},{id:2,text:'duplicate'}];
callback(data);
}
}).select2('val', ['1', '2']);
演示: 小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.