如果用户未确认[关闭],则在模糊时撤消文本更改

问题描述 投票:0回答:3

当用户离开文本框时,我想弹出一个确认,询问他们是否确定要进行更改。如果他们回答否,那么我希望文本框撤消他们的更改。

有一种非常简单的方法可以做到这一点,还是我必须手动跟踪自己的初始值是什么?

(我知道怎么做确认,只是询问撤消部分)

javascript jquery html5
3个回答
3
投票

您必须存储旧值,但是对于在每个确认的更改时设置的变量,这很简单:

let lastConfirmedValue = "";  // Last good value is stored here

document.querySelector("input").addEventListener("change", function(evt){
  if(confirm("Are you sure?")){
    lastConfirmedValue = this.value;  // Update the last committed value
  } else {
    evt.preventDefault();             // Cancel the event
    this.value = lastConfirmedValue;  // Put old value back
  }
});
<input>

既然你问过defaultValue,那么让我告诉你它是如何工作的:

let txt1 = document.getElementById("one");
let txt2 = document.getElementById("two");


console.log("Box 1 defaultValue: " + one.defaultValue,
            "Box 2 defaultValue: " +  two.defaultValue);
            
// Now change the values of both
txt1.value = "something";
txt2.value = "somthing else";

console.log("Box 1 defaultValue: " + one.defaultValue,
            "Box 2 defaultValue: " +  two.defaultValue);
            
// Now change the values of both again
txt1.value = "abc";
txt2.value = "xyz";

console.log("Box 1 defaultValue: " + one.defaultValue,
            "Box 2 defaultValue: " +  two.defaultValue);
<input id="one">
<input id="two" value="CT">

0
投票

0
投票

您可以侦听相应的事件,然后在发生这些事件时采取措施:

const inputEl = document.querySelector('#inputEl');
let temp;

//Update the temp value each time we focus on the input
inputEl.addEventListener('focus', e => {
  temp = e.target.value;
});

//Confirm that the user wants to keep their changes
inputEl.addEventListener('change', e => {
  var confirmed = confirm('Are you sure you want to save these changes?');
  if (!confirmed) {
    e.target.value = temp;
  }
})
<label for="inputEl">Enter a value</label>
<input id="inputEl" type="text">
© www.soinside.com 2019 - 2024. All rights reserved.