How to show the “Are you sure you want to navigate away from this page?” when changes committed?

前端 未结 17 1789
深忆病人
深忆病人 2020-11-22 02:11

Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: \"Are you sure you want

17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 03:07

    This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:

    $(function () {
        $("input, textarea, select").on("input change", function() {
            window.onbeforeunload = window.onbeforeunload || function (e) {
                return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
            };
        });
        $("form").on("submit", function() {
            window.onbeforeunload = null;
        });
    })
    

提交回复
热议问题