How to capture old value and set it back on cancel using javascript

♀尐吖头ヾ 提交于 2019-12-03 16:05:47

Note that form controls have a defaultValue property that is the default value (surprisingly). You can use this property to store the previous value of the input, or to return the value to the previous value.

So putting together the suggestions you've been given, the following function is passed a reference to the element and asks the user if they want to keep the current value. If they answer yes, then the defaultValue of the input is set to the current value. If the users says no (i.e. cancel), then the value is reset to the defaultValue.

Note that this approach will overwrite the original value of the input, so if you reset the form, the input's value will be reset to the current defaultValue.

<script>
function onChangeOfValue(element) {
  var oldValue = element.defaultValue;
  var newValue = element.value;
  if (window.confirm('do you really want to change the value to ' + newValue + '?')) {
    element.defaultValue = newValue;
  } else {
    element.value = element.defaultValue;
  } 
}
</script>

<input onchange="onChangeOfValue(this);">

This approach will work for any number of inputs in the same page and form.

I would use a closure to keep track of the last value:

(function(){ 
    var oldValue = document.getElementById(input).value;
    document.getElementById(input).onchange = function(){
        var newValue = this.value;
        alert("newVal is--->"+newValue);
        if(document.getElementById(input) != null 
            && document.getElementById(input) != '' 
            && !confirm("Do you want to continue?")){

            this.value = oldValue;
            return false;
        } else {
            oldValue = this.value;
        }
    };
})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!