Skip to content Skip to sidebar Skip to footer

Editing Prompt In Javascript

In my web application, I have a page with several input values, and would like to confirm that the user wants to leave the page if the user tries to leave with unsaved information

Solution 1:

You'll need to use the change event on all your inputs to detect any changes made by the user. This event doesn't bubble, so you'll need to attach it to each input individually. Then you'll need to use the beforeunload event of the window object to prompt the user.

<script type="text/javascript">
    var anythingEdited = false;

    function inputChanged() {
        anythingEdited = true;
    }

    window.onbeforeunload = function(evt) {
        if (anythingEdited) {
            evt = evt || window.event;
            evt.returnValue = "You have edited something. If you click OK, your changes will be lost.";
        }
    };
</script>

First name: <input type="text" id="firstName" name="firstName" onchange="inputChanged();">

Post a Comment for "Editing Prompt In Javascript"