How to alert when unload page while checking whether each element is changed or not
I developed page in which multiple input
and textarea
exist.
I would like to set unload event to prevent what we inputed are not inserted.
To set this,I also add checking whether each input elements are changed.
If text are changed. I would like to set this alert system.
while these texts are not changed, we can easily leave page and unload
event will not be fired.
I have tried following . I would like to combile window.addEventListener('beforeunload')
and window.addEventListener('load')
. are there any good ways to achieve this?
My point is how to handle beforeUnloadAlert
variables..
Thanks
window.addEventListener('beforeunload', function(e) {
e.returnValue = 'Are you sure you want to exit?';
}, false);
window.addEventListener('load', function (e) {
let beforeUnloadAlert = true;
var inputs = document.querySelectorAll('.inputForm');
for (var i = inputs.length - 1; i >= 0; i--) {
inputs[i].addEventListener('change', displayName);
}
function displayName(e) {
console.log(this);
beforeUnloadAlert = false;
}
return befo开发者_如何学运维reUnloadAlert
});
<input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'>
精彩评论