【问题标题】:Select2: How to get previous selected valuesSelect2:如何获取先前选择的值
【发布时间】:2016-09-08 03:37:27
【问题描述】:

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

【问题讨论】:

    标签: javascript select2


    【解决方案1】:

    可以通过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());
    });
    

    【讨论】:

      【解决方案2】:

      您可以在选择事件时轻松完成

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

      【讨论】:

        【解决方案3】:
        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
        });
        

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
        猜你喜欢
        • 1970-01-01
        • 2016-03-31
        • 2010-09-20
        • 2018-02-19
        • 1970-01-01
        • 2013-11-23
        • 2018-01-29
        • 1970-01-01
        • 2018-03-20
        相关资源
        最近更新 更多