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; }); });
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With