I need to implement in JS a warning if a user changes an input field in a form without saving. The expected behavior is that I make a change into the input and if I try to close the window the confirm dialog appears.
However, what actually happens is when I close the window, the window closes and the dialog does not appear.
I'm referencing the following resources:
Warn user before leaving web page with unsaved changes
JavaScript before leaving the page
This is what I have currently:
var formInputChanged = false;
$(function() {
// activate modal is field is edited
$(".account-settings-form input").on("input", function() {
window.formInputChanged = true;
});
$("input[value='Cancel']").click(function() {
window.formInputChanged = false;
});
window.addEventListener('beforeunload', (event) => {
if (window.formInputChanged) {
confirm("You have unsaved changes");
}
});
});
I have that variable set globally so as far a I understand, should be fully accessible and I'm assigning it to the window in the functions.
I can see in the console.log() that formInputChanged
is the correct value.
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.
What does "leave the page" mean? Back button? X out? Is it an event listener issue?
According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.
I have that in place so that doesn't seem to be the issue...
Why doesn't the confirm modal launch?
Here is a full JS Fiddle demo: https://jsfiddle.net/g6wjrcae/