[英]Proper usage of jQuery select2's initSelection callback with remote data
I use jQuery select2 plugin in order to retrieve postcodes using the provided ajax callback function as follows: 我使用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
};
})
};
}
}
});
});
Once two postcodes are selected I get the resulting hidden input
in the DOM: 一旦选择了两个邮政编码,我就会在DOM中得到
hidden input
:
<input type="hidden" class="bigdrop select2-offscreen" id="postcodes" style="width:600px" name="familyAdvertisement.postcodes" value="4797,4798" tabindex="-1">
The issue I have is that once the form is redisplayed (for instance in the event of some other controls being in error), the selections (ie the two postcodes and especially the text
) don't show in the form although the hidden input
does have the two values (ie 4797 and 4798, which are the id
s for the postcode). 我遇到的问题是,一旦重新显示表单(例如,在某些其他控件出错的情况下),虽然
hidden input
确实存在,但选择(即两个邮政编码,尤其是text
)不会在表单中显示有两个值(即4797和4798,这是邮政编码的id
)。
I am not sure if I have to do another ajax round trip when the form is redisplayed or if there is a better way to go. 我不确定如果重新显示表单或者有更好的方法,我是否必须再做一次ajax往返。
Can anyone please advise? 任何人都可以建议吗?
The initSelection method has to pass the values which has to be present in the select2
initSelection方法必须传递必须存在于
select2
Ex: 例如:
$("#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.