Ed

Ed

  • NA
  • 3
  • 0

Trapping the window close button but not during postbacks

Dec 3 2009 4:20 PM

I have a C# .net application that is used for data entry.  If the users enter changes on the screen in textboxes or dropdown boxes and try to close the window with the X button, I need to warn them that they will loose thier changes if they don't save first.
So I built a javascript function to trap the beforeunload event which works well.  However, it fires whenever the page has a postback.  And I need to do postbacks on the data entry dropdown boxes.
So my question is this:  How can I get this thing to fire only when the X button is pressed?  Is there any way to detect if the beforeunload event is happening as a result of a postback being initiated?  Can you distinguish between the X button being pressed and a postback?  I know you can detect if a postback has occured, but by then its too late.  As far as I can figure this needs to be done before the postback occurs, not after.
I've posted my code below.    Also, If anyone has a good alternative way to handle this entire senairo I'd love to hear it.  The requirements are: 1. warning the users that thier changes have not been saved.  2. the web page must allow for postbacks to occur.
function showalert()
{
var ChangesMade = document.forms[0]['txtChangedStatus'].value;
if (ChangesMade == 'Y') {event.returnValue = "You've made changes to this call but did not save them."; }
}

Answers (2)