How to capture old value and set it back on cancel

2019-03-30 05:14发布

问题:

I have a text field from which I am calling a function on onChange event. I am throwing a confirm window here when the value in that textfield is changed. If cancel is clicked( in confirm window), the old value must get set back into the text field. If proceed or ok is clicked, the new value should be retained. I have been trying this for a long time but am unable to retain the old value.

Eg: Before onchange, val in text field ='first'; onChange event, val changed to 'second', confirm window opens, if ok selected text field should have second and if cancel is selected 'first' should be present in the text field.

function onChangeOfValue(input){
    //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.input=oldValue;
        return false;
    }
    }

}

回答1:

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.



回答2:

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