Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery warn if leaving page without clicking the save button

Tags:

jquery

The following code executes a warning if you change data on the page and then leave the page. I want that - except when the user presses the save button.

This is the jquery code:

$(document).ready(function() {   formmodified=0;     $('form *').change(function(){         formmodified=1;     });   window.onbeforeunload = confirmExit;     function confirmExit() {       if (formmodified == 1) {           return "New information not saved. Do you wish to leave the page?";       }   } }); 

This is the button that saves the data:

<input class="btn-primary" name="commit" type="submit" value="Save Material"> 

UPDATE Thanks tymeJV !!!!!!!

In case someone else need it, this works:

$(document).ready(function() {     formmodified=0;     $('form *').change(function(){         formmodified=1;     });     window.onbeforeunload = confirmExit;     function confirmExit() {         if (formmodified == 1) {             return "New information not saved. Do you wish to leave the page?";         }     }     $("input[name='commit']").click(function() {         formmodified = 0;     }); }); 
like image 402
Reddirt Avatar asked May 01 '13 16:05

Reddirt


People also ask

How to display warning before leaving the web page with unsaved changes using JavaScript?

How to display warning before leaving the web page with unsaved changes using JavaScript ? The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources.

Which jquery event method will show an alert before the user leaves the page?

The onbeforeunload event fires when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What JavaScript event do we use to make the user confirm before leaving the page?

To make a warning alert or confirm dialog display when the user reloads the page or closes a tab using javascript, we can use window. addEventListener() and beforeunload events like the script above.


1 Answers

Given your save button info:

<input class="btn-primary" name="commit" type="submit" value="Save Material"> 

You can set the value of formmodified

$("input[name='commit']").click(function() {     formmodified = 0; }); 

Your check at the end shouldn't be triggered now

like image 127
tymeJV Avatar answered Oct 03 '22 11:10

tymeJV