简体   繁体   中英

launch confirm dialog if user changes input without saving

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/

In the conditional you add:

event.returnValue = "";
            return "";

So:

window.addEventListener('beforeunload', (event) => {
        event.preventDefault();
        if (window.formInputChanged) {
            event.returnValue = "";
            return "";
        }
    });

Try this in handler for "beforeunload"

window.addEventListener("beforeunload", function (e) {
    if(formInputChanged) {
        var confirmationMessage = "You have unsaved changes";

        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    }
}); 

I believe confirm("You have unsaved changes"); is where your issue is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM