Javascript to warn the user that they will lose data if they go away from this page

/ Published in: JavaScript
Save to your folder(s)

Easy to use in C# ASP.NET:
to prevent a user from losing data when navigating away from whatever page they are on, just add
string setConfirmUnload = "setConfirmUnload(true);";
ScriptManager.RegisterStartupScript(this, this.GetType(), "", setConfirmUnload, true);
to you code somewhere, or just call
from the onClick or onClientClick even of a link.
To allow a link to navigate away, pass in false instead.

Might be handy on an ASP.NET master page.

Copy this code and paste it in your HTML
  1. function setConfirmUnload(on) {
  2. window.onbeforeunload = (on) ? unloadMessage : null;
  3. }
  4. function unloadMessage() {
  5. return 'You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.';
  6. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.