开发者

Ask for confirmation on page unload

On StackOverflow when you're asking a new question, you have enter the question and if you decide to navigate away from the page you get an "Are you sure" confirmation.

I'd like to do the same in my ASP.Net application:

The user has to fill开发者_StackOverflow in a questionnaire and has the option to store his answers temporarely. If the user decides to navigate away from the page without temporarely storing his answers we'd like a confirmation to popup and ask the user to store his answers.

Two questions:

  • What's a decent way of showing the confirmation popup before the page unloads in ASP.Net?

    I'm aware of the beforeunload event, but I don't want to make it one big javascript hack.

  • I don't want the confirmation to kick in when the user clicks the Save button (which is saving the answers anyway)


You have to write the action in

onbeforeunload Event

which fires prior to a page being unloaded.

<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>


You should pay your attention on "onbeforunload" event As for the Save button you just can make some scripting logic, for example unsubscribe on this event or else.


You can try this:

<button onclick="javascript:doSend()">send</button>
<button onclick="window.xbuttons +='save ';">save</button>
<button onclick="window.xbuttons +='edit';">edit</button>
<script>
   window.xbuttons = '';
   window.onbeforeunload = function(){
      if(!window.xbuttons.match(/save|edit/))
         return "Do you want to leave this page?";
   }
</script>

Here are the things you should note about onbeforeunload:

  1. onbeforeunload event will fire on every a (anchor elements) with href attribute
  2. onbeforeunload event will fire when the document location is change via javascript or by changing the url on the address bar
  3. onbeforeunload event will fire on any event that uses javascript: pseudo-protocol
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜