javascript Select2:如何获取先前选定的值

aiazj4mn  于 2023-05-16  发布在  Java
关注(0)|答案(5)|浏览(207)

我用的是select v4.0.3。如何获取select元素的replaced/previous值?我已经附加了一个'更改'侦听器,但我似乎找不到以前的值。

2o7dmzc5

2o7dmzc51#

可使用select2:selecting事件获取先前选择的值
代码在这里:https://codepen.io/jacobgoh101/pen/ZpGvkx?editors=1111

$('select').on('select2:selecting', function (evt) {
  console.log('previously selected ' + $('select').val());
});
$('select').on('select2:select', function (evt) {
  console.log('now selected ' + $('select').val());
});
xe55xuns

xe55xuns2#

您可以在selecting事件中轻松完成此操作:

$(this).on("select2-selecting", function(e) {
  var curentValue = e.val;
  var previousValue = $(this).val();
});
qmb5sa22

qmb5sa223#

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
});
wgxvkvu9

wgxvkvu94#

这将处理Select2的选择,在Select2中,您可以获得旧值和新值,并在需要时比较它们

$('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'
});
vuktfyat

vuktfyat5#

//获取先前选择的值

$(document).on('select2:selecting', 'select', function (evt) {
   console.log('previously selected value :' + $(this).val());
});

//获取当前选择的值

$(document).on('select2:select', 'select', function (evt) {
   console.log('current selected value : ' + $(this).val());
});

//如果你想为一个特定的select执行这个函数,使用如下的类

$(document).on('select2:selecting', 'select', function (evt) {
   if ($(this).hasClass("select_email_type")) {
      console.log('previously selected value :' + $(this).val());
   }
});

相关问题