Using onbeforeunload to create a custom confirmation warning?

236 views Asked by At

I'm trying to create a custom alert function for a website. It checks if there is anything in some form fields, and if there is, it should display a confirmation message if you're trying to navigate away. (Excluding the submit and cancel button.)

I have this code to check for the data, and navigation excluding certain buttons:

 var leave_page_confirm = true;

                        function save_data_check() {
                            var msg;
                            if (leave_page_confirm === true) {
                                $('.input-right').each(function() {
                                    if (this.value) {
                                        leave_page_alert();
                                    }
                                });
                            }
                        }

window.onbeforeunload = save_data_check;

Buttons that I want to exclude from being seen as navigating away from the page will contain:

onclick="leave_page_confirm=false;"

The leave_page_alert function is defined like this:

var leave_page_alert = function() {

  $("#custom-alert-overlay").show();

}

Without knowing the CSS and HTML, it suffices to say that "custom-alert-overlay" is the id of the element which will contain the buttons.

What I'm stumped on is what to add to "leave_page_alert()" in order to prevent the page from loading until one of the buttons is clicked.

For arguments sake, suppose that "custom-alert-overlay" contains these buttons:

<button type="button" id="stay">Stay on this Page</button>
<button type="button" id="leave">Leave this Page</button>

Despite Googling around, I haven't managed to dig up exactly how one would do this...

0

There are 0 answers