如何在更改事件的jquery中获取textbox的先前值

时间:2017-07-06 14:32:26

标签: javascript jquery

 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });

我想在更改事件中存储以前的值如何在jquery中执行我无法使用$(this).data(“old”)存储值;任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

您几乎做对了,但是您忘记更新代码中的data-old,下面是一个示例jsbin

 $(".whitebox").on('change', function (event) {
   // on first change will be empty string
   // as no previous value was set
   var oldValue = event.target.dataset.old;
   console.log('old value', oldValue);

   // your code here

   // at the end assign new value to data-old attribute
   $(this).data('old', event.target.value);
   console.log(event.target.value);
 });

http://jsbin.com/jasaqiwuwo/

答案 1 :(得分:0)

var prevVal = $('input').val(); //init val
var valuesHistory = [prevVal]; 
$('input').data('prevData', prevVal);

$('input').on('change', function() {
  console.log('prev value from data: ', $(this).data('prevData'));
  console.log('prev value from var: ', prevVal);
  console.log('log: ', valuesHistory);
  valuesHistory.push($('input').val());
  $('input').data('prevData', $('input').val());
  prevVal = $(this).val();
});
// you can also get the prev value, like that valuesHistory[valuesHistory.length-2];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">

答案 2 :(得分:0)

试试这个:

htop

然后使用您的更改活动。

相关问题