Select2:如何获取之前选择的值

问题描述 投票:0回答:4

我正在使用 select v4.0.3。如何获取 select 元素的替换/先前值?我已经附加了一个“更改”侦听器,但我似乎找不到以前的值。

javascript jquery-select2
4个回答
10
投票

可以使用

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

6
投票

你可以在选择事件中轻松做到:

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

0
投票
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
});

0
投票

这处理 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'
});
© www.soinside.com 2019 - 2024. All rights reserved.