jQuery: Show Window.OnBeforeUnload Warning except Submit Button was clicked
Tip by Stefan Trost | 2016-10-07 at 20:17
With Window.OnBeforeUnload it is possible to show a warning to the user when he is about to leave the page. Window.OnBeforeUnload becomes active when trying to close the corresponding tab or the whole browser. However, it also becomes active when only clicking the submit button of the form - a case in which there is no risk that the user input could get lost.
This is the reason why I want to show you a solution with which you can ensure that the Window.OnBeforeUnload is only displayed if the submit button was not pressed:
var submitted = false; $(document).ready(function() { $("form").submit(function() { submitted = true; }); window.onbeforeunload = function () { if (!submitted) { return 'Do you really want to leave the page?'; } } });
The variable "submitted" should indicate whether the submit button was already clicked. Correspondingly, first, we are setting this variable to "false".
In the moment when clicking the submit button of our form, we are setting "submitted" to "true" to be able to show the wanting in our window.onbeforeunload function only in the opposite case.
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile
Related Topics
JavaScript: Show warning when leaving the page
Info | 0 Comments
jQuery: Submit complete form and receive content with Ajax
Tutorial | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
jQuery: Disable Submit Button if no Checkbox is selected
Tutorial | 7 Comments
Delphi/Lazarus: ShowModal Result
Tip | 0 Comments
jQuery: Note when leaving a website and a form has not been submitted
Tutorial | 2 Comments
Mouseover buttons using CSS without reloading
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Uncaught ReferenceError: $ is not defined
$(document).ready(function() {
2022-11-05 at 14:21
When you get that error, you have forgotten to include the jQuery framework on which the code above is based. As you can see, it's a jQuery solution here, so you have to include it.
2022-11-05 at 15:31