var oldname;//global declaration
$('select').on('select2:selecting', function (evt) {
oldName= $('select').val();
});
$(select).on("select2:select select2:unselecting", function (e) {
//For selecting the new option
var currentName= $(this).select2('data')[0].text;
console.log(oldName);//you can get old name here also
});
$('select').on('select2:selecting', function (evt) {
var oldSelect2Value = $(this).val();
evt.preventDefault(); //this prevents any value from being changed yet
var newSelect2Value = evt.params.args.data.id;
//and if you want to set the new value:
var conditionToChangeValue = true; //you can put any condition here if you want to apply the new value or keep the old value
if(conditionToChangeValue){
//this sets thew new value you have selected :
$(this).val(newSelect2Value).trigger('change').select2("close"); //it needs to be closed manually
}
else{
//this here keeps the old value;; you don't need to write extra code to apply the old value since it already has that value
}
});
如果你只想手动触发'select2:selecting':
var someSelect2Value = "1";
$('select').val(someSelect2Value).trigger('change').trigger({
type: 'select2:selecting'
});
5条答案
按热度按时间2o7dmzc51#
可使用
select2:selecting
事件获取先前选择的值代码在这里:https://codepen.io/jacobgoh101/pen/ZpGvkx?editors=1111
xe55xuns2#
您可以在selecting事件中轻松完成此操作:
qmb5sa223#
wgxvkvu94#
这将处理Select2的选择,在Select2中,您可以获得旧值和新值,并在需要时比较它们
如果你只想手动触发'select2:selecting':
vuktfyat5#
//获取先前选择的值
//获取当前选择的值
//如果你想为一个特定的select执行这个函数,使用如下的类