Prevent users from accidentally moving from unsaved pages

I got the snippet below this SO post, and it works when the user tries to reload the page or close the browser, etc., but if the user clicks the link, he allows them to naively wave off, and then incorrectly displays the message on the wrong page. I use pjax for links.

$(document).ready(function () { $('textarea').change(function () { window.onbeforeunload = function () { return "Your changes to the survey have not been saved?" }; }); }); 
+4
source share
2 answers

You should use onbeforeunload as follows:

 <script type="text/javascript"> saved=true; // initially, it is saved (no action has been done) window.onbeforeunload = confirmExit; function confirmExit() { if (!saved) { return "You did not save, do you want to do it now?"; } } </script> 

This event cannot be processed only when another event is fired. The onchange event of your text field here probably does not fire before you click on the link so that the window does not process onbeforeunload at all. The link will work as expected: you will be redirected.

To deal with the saved flag, you can listen to what is happening in your text field, for example, when the user is actually typing:

 $('textarea').keyup(function(){ saved=false; }); 

Then, if you save the data in ajax, the save button can return true:

 $('#btnSave').click(function(){ // ajax save saved=true; }); 

Otherwise, it will load the next page with the saved flag.

+8
source

what about the next one? Listening to all links <a> , and then, depending on whether the value of the needToSave variable is set to true, the message is displayed or its resolution.

 var needToSave = false; // Set this to true on some change // listen on all <a ...> clicks $(document).click("a", function(event){ if (needToSave == true) { alert("You need to save first"); event.preventDefault(); return; } }); 

UPDATE (according to Roasted's suggestion) this should trigger an unload event every time the link is clicked and execute the existing logic:

 // listen on all <a ...> clicks $(document).click("a", function(event){ $(window).trigger("unload"); }); 

jsFiddle here - http://jsfiddle.net/k2fYM/

+3
source

Source: https://habr.com/ru/post/1495492/


All Articles