[英]How to show message to user if they are trying to leave the page or close the window only if form data has been changed?
I have requirement in one of my projects where users would like to see a message before they leave the page or close the browser/window if the form data has been changed.我在我的一个项目中有一个要求,如果表单数据已更改,用户希望在离开页面或关闭浏览器/窗口之前看到一条消息。 I found this function that will catch the scenario if user is leaving the window or closing the browser.
我发现这个函数可以在用户离开窗口或关闭浏览器时捕捉场景。
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
I'm wondering if there is a way to show that message only if form data has been changed.我想知道是否有一种方法可以仅在表单数据已更改时显示该消息。 SO user in that case would know that data has changed.
在这种情况下,SO 用户会知道数据已更改。 I did not find a lot about this topic or any constructive solutions so far.
到目前为止,我没有找到很多关于这个话题或任何建设性的解决方案。 If anyone have any examples or suggestions please let me know.
如果有人有任何示例或建议,请告诉我。
Thank you.谢谢你。
If you're not using any modern framework you can build your custom Form State helper.如果您不使用任何现代框架,您可以构建您的自定义表单状态助手。 When form is ready on DOM you can iterate over each input element and assign a data property say (data-init-val) and set its value equal to the input element value.
当表单在 DOM 上准备好时,您可以迭代每个输入元素并分配一个数据属性 say (data-init-val) 并将其值设置为等于输入元素值。
let inputs = document.querySelectorAll('form#userform input');
for(let inputEl of inputs){
inputEl.setAttribute('oldVal', inputEl.value);
}
This way you're caching the existing form values.这样您就可以缓存现有的表单值。 When user is closing the window you can run a function to compare current input values with the initial cached values via:
当用户关闭窗口时,您可以运行一个函数,通过以下方式将当前输入值与初始缓存值进行比较:
function checkFormState(){
let inputs = document.querySelectorAll('form#userform input');
let stateChanged = false;
for(let inputEl of inputs){
if(inputEl.getAttribute('oldVal') !== inputEl.value){
stateChanged = true;
break;
}
}
return stateChanged;
}
Your eventListener can make an informed decision based on the stateChanged value.您的 eventListener 可以根据 stateChanged 值做出明智的决定。 PS: You should modify the input element value caching/compare logic based on the input elements in your form.
PS:您应该根据表单中的输入元素修改输入元素值缓存/比较逻辑。
Headover to https://jsfiddle.net/v9rztay6/ and see it in action.转到https://jsfiddle.net/v9rztay6/并查看它的运行情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.