首页 > 解决方案 > 从更改事件中获取旧值

问题描述

我正在使用标记为 .html 的 html 表单date。我想在.change调用后检查旧值

我的代码:

$('#date').change(function(event) {
        event.preventDefault();
        $('#list_data').html('');
        $('#btndownload').hide();
        $('#btngenerate').hide();
        val = $(this).val(); //want to change it to old/previous value
        if(val || val !=""){
            console.log("this value: " +val);
            $('#btnview').show();
        }
        else{
            $('#btnview').hide();
            console.log("closed");
        }
    });

任何线索?

标签: javascriptjqueryhtml

解决方案


您可以将旧值保存在可以使用.data()方法操作的缓存中。

此外,如果需要,使用defaultValue属性来获取创建此对象的 HTML 中最初指定的默认值。可以使用.prop()方法获取

$('#date').change(function(event) {
  var currentValue = $(this).val();
  var previousValue = $(this).data('previousValue');
  
  //if you want to get original value set in html
  var defaultValue = $(this).prop('defaultValue');  

  //set currentValue as previousValue
  $(this).data('previousValue', currentValue);
  
  console.clear();
  console.log("previousValue: " + previousValue);
  console.log("currentValue:" + currentValue);
  console.log("defaultValue: " + defaultValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" value="2020-01-21">


推荐阅读