Babu Babu - 6 months ago 17
Javascript Question

Windows beforeunload gives alert message even though there is no pending changes to save

I am using the following jQuery to alert user when they navigates away from given page without clicking save/update button. It works as expected but it gives the alert message even though there is not any pending changes left to save. It alert the user when they saved all the changes they made and try to navigates away from the page. I want it to alert only if they didn't save their changes.

$(document).ready(function () {
var unsaved = false;
$(window).bind('beforeunload', function () {
if (unsaved) {
return "You have made some changes. Save your pending changes before existing the page";
}
});
// Monitor dynamic inputs
$(document).on('change', ':input', function () {
unsaved = true;
});
})

Answer

try this it should works for you:

//alert user for unsaved changes 
        $(document).ready(function () {
            // Monitor dynamic inputs
            $(document).on('change', ':input', function (e) {
                $(this).addClass('changed-input');
            });

            $(window).on('beforeunload', function () {
                if ($('.changed-input').length) {
                    return 'You haven\'t saved your changes.';
                }
            });
        })