javascript – window.onbeforeunload not working as expected-ThrowExceptions

Exception or error:

I have created the following jsfiddle.

If you enter any input in any of the edit boxes and try to leave the page a warning is displayed which is ok.

If you enter any input and click on the button the warning is still displayed when the requirement is not to be. (I need to prevent it from displaying).

In the webpage it seems that window.onbeforeunload is thrown earlier than the on click event so it will always display the warning dialog even if you click the submit button.

It makes me think that the code should change to deal with the timing of the events but not sure?

How to solve:

It sounds like what you want to do is to prevent the onbeforeunload message from showing when you submit the form.

Simply add a submit handler that returns the form_has_been_modified value to false.

$("#additemform").on('submit', function(e) {
    form_has_been_modified = false;
});

Working Demo

In this demo I also cleaned up your example, removing unnecessary handlers and changed form_has_been_modified to use the native boolean true and false instead of 0 and 1.

Leave a Reply

Your email address will not be published. Required fields are marked *