Search code examples
javascriptonbeforeunload

Don't show onbeforeunload alert when hitting submit


I have the following function to show a alert when the visitor hits "cancel" or trying to go back with filled textfields. The function works perfectly overall but not when I'm hit submit. The alert shows when I hit the button and I don't want it that way.

var changed_flag = 0;

$('input').change(function() {
    changed_flag = 1;
});

window.onbeforeunload = function() {
    if(changed_flag) {
        return 'You haven't saved your work!'
    }
};

I know I should edit the $('input').change(... and add input[type="submit"] but I don't know how and where. Do anyone know how I can fix this problem?

Thanks in advance.


Solution

  • Try

    $('form').submit(function() {
        changed_flag = 0;
    });