Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warn User When Navigating from Page with Unsaved Changes

I'm creating an ASP.NET website and I want to implement logic to warn the user when they are navigating away from a page they've edited.

I found quite a bit of info on the web, although most of it seems quite outdated. 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 is supposed to be equal to the code above only when a change is made--does not work. No warning is ever displayed.

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

Can someone say why the second snippet doesn't work? Or perhaps you can point me to a reference that is more recent.

like image 675
Jonathan Wood Avatar asked May 15 '26 17:05

Jonathan Wood


1 Answers

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

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?" };
  });
});
like image 178
Digital Plane Avatar answered May 18 '26 08:05

Digital Plane