views:

439

answers:

2

I have the following Jquery function to notify the user with a prompt when they have unsaved changes (similar to how SO does it) and are trying to leave the current screen.

<!-- in my aspx page -->
<script type="text/javascript" language="javascript">
    window.onbeforeunload = function()
    {
        if (HasPendingUpdates())
        {
            return "Changes you have made will not be saved.";
        }
    }
</script>

This works as expected and shows the message box when the user tries to click a href to browse away or use the back button etc. The problem I am having is that one of my links is a asp:LinkButton because it needs to fire off some server side code before leaving the page. When the user clicks this LinkButton they get the prompt twice.

Scenarios:

  1. User clicks the LinkButton
  2. Prompt appears and user clicks the cancel button.
  3. Prompt disappears and user is still on screen. GOOD.

  4. User clicks the LinkButton

  5. Prompt appears and clicks the OK button.
  6. Prompt disappears and the same prompt shows again.
  7. User clicks OK again.
  8. Prompt disappears and user moves to the next screen and all is good.

So why am I getting the second prompt??? How is the OnBeforeUnload firing twice?

A: 

Adding handlers with jQuery stacks them. If you're assigning a handler with some jQuery function for your hrefs and then assigning it again for your linkbutton, there will be two handlers in place.

Check how often you are binding the onunload handler, and make sure that you're either unbinding previous handlers or only doing it once.

womp
I am not assigning the handlers specifically to any controls. The Jquery function executes on page load and assigns the function to the window.onbeforeunload. The page is never loaded more than once so the Jquery code should only bind once. All other links, back button, etc do not cause a double prompt.
Kelsey
+1  A: 

This has to do with the way that IE processes the href that a LinkButton generates. I was able to find a piece of jQuery code someone had written to manage this issue.

Or you could change the LinkButton in to a regular Button, if that's an option.

CAbbott