如何使用javascript捕获旧值并将其重新设置为取消 [英] How to capture old value and set it back on cancel using javascript

查看:82
本文介绍了如何使用javascript捕获旧值并将其重新设置为取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,我在 onChange 事件中调用该函数。当文本字段中的值发生变化时,我在这里抛出一个确认窗口。如果单击取消(在确认窗口中),则必须将旧值设置回文本字段。如果单击继续或确定,则应保留新值。
我已经尝试了很长时间但是我无法保留旧值。

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.

例如:
在onchange之前,val在文本字段中= '第一';
onChange事件,val更改为'second',确认窗口打开,如果ok选择文本字段应该有秒,如果选择取消'first'应该出现在文本字段中。

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

}


推荐答案

请注意,表单控件具有 defaultValue 属性,这是默认值(令人惊讶)。您可以使用此属性存储输入的先前值,或将值返回到先前的值。

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.

因此,将您给出的建议放在一起,以下函数传递对元素的引用,并询问用户是否要保留当前值。如果他们回答是,则输入的 defaultValue 将设置为当前。如果用户拒绝(即取消),则将重置为 defaultValue

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.

请注意此方法将覆盖输入的原始,因此,如果重置表单,则输入的将重置为当前 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.

这篇关于如何使用javascript捕获旧值并将其重新设置为取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆