Warn user before leaving page with unsaved changes

  • Thread starter Thread starter markalroberts
  • Start date Start date
M

markalroberts

Hi,

I wish to ask warn the user that there are unsaved changes (if there
are) and allow them to cancel navigating away/closing the browser.

Investigation leads me to believe the "OnBeforeUnload" event is the
best bet - this does as I wish... Except it doesn't distinguish between
hyperlinks within the site and hyperlinks outside it.

I.e. simple Hyperlink button will raise the Unload event when clicked,
as will closing the window, but I'm only interested in the Closing
window one, and there doesn't appear to be any way to tell them apart.

If someone could help here, it would be very useful!
Thanks,
Mark.
 
I've done something similar to that. Ignoring the hyperlinks and only
responding to a close involves some manual coding. Start with this
block of javascript.

var IsLinkClicked = false;

function CheckUnload()
{
if (!IsLinkClicked && ("1" ==
document.forms["Form1"].IsChanged.Value))
{
if (confirm("You have unsaved changes. Click OK to save changes."))
{
document.forms["Form1"].submit();
alert("Changes saved.");

return false;
}
}
}

First thing, you'll want to set a hidden fields 'IsChanged' to true
whenever you make a change that should be saved. This way you'll only
prompt when a change has actually been made. Secondly, if the user
clicks on any hyperlinks on your page you need to set 'IsLinkClicked' =
true using javascript whenever a user clicks on a link. That way you'll
only prompt when the user closes the window or manually types in a new
address into the URL bar.

Instead of a hidden field for IsChanged, you could probably implement
this as a javascript variable also.
 
When it is a planned navigation (like hiperlink , button etc) set a
javascript variable and check this variable in OnBeforeUnload to determine
whether to display warning message or not ..

for eg, declare javscript variable

var warn_pageunload = true;

Fron button click , link click etc set

warn_pageunload =false;

In the unload event

if(warn_pageunload == true)
{
\\code to warn user
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top