Airikr
Airikr

Reputation: 6446

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.

Upvotes: 1

Views: 2277

Answers (3)

David Hellsing
David Hellsing

Reputation: 108530

Try

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

Upvotes: 2

SpliFF
SpliFF

Reputation: 39014

Just have your submit button remove the event or set changed_flag back to 0.

<input type="submit" onmousedown="changed_flag = 0" />

EDIT: On second thoughts put this code in your onsubmit handler in case the form is submitted some other way (like pressing enter or via another function).

Upvotes: 0

Andy Ray
Andy Ray

Reputation: 32076

$('form').submit(function() {
    $(window).unbind('beforeunload');
});

Alternatively instead of the unbind you could just do changed_flag = 0

Upvotes: 0

Related Questions