Warn user when navigating from page with immediate changes

I am creating an ASP.NET website and I want to implement logic to alert the user when he moves from the page they edited.

I found quite a bit of information on the Internet, although most of them seem pretty dated. Please note that I still have a lot to learn about jQuery.

The following code displays the message as expected.

window.onbeforeunload = function () { return 'You have unsaved changes!'; } 

However, the following code, which should be equal to the above code only when making changes, does not work. A warning is never displayed.

 $('input').change(function () { window.onbeforeunload = function () { return "Your changes have not been saved?" }; }); 

Can someone tell me why the second snippet is not working? Or maybe you can give me a link that is later.

+2
source share
1 answer

Input elements probably do not exist when the code is executed. Try using the .live function to detect changes in all input elements or to wrap your code in $(document).ready() .

Example:

 $('input').live("change", function () { window.onbeforeunload = function () { return "Your changes have not been saved?" }; }); 

or

 $(document).ready(function () { $('input').change(function () { window.onbeforeunload = function () { return "Your changes have not been saved?" }; }); }); 
+6
source

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


All Articles