views:

4466

answers:

2

I have a small problem. I'm attempting to catch the OnUnLoad Event of the Window and ask a confirmation question and if the user decides they want to stay then fine, and if they want to leave the page then they'll lose all unsaved data. Here's the issues...

I'm using a jQuery UI Dialog and when I put the following code on my page, I have the Dialog open, and when I click the back button on the browser, it never pops up the msgbox. It just refreshes the page:

<script type="text/javascript"> 
    $(window).bind('beforeunload', function() 
        { 
            alert('you are an idiot!'); 
        } 
    );
</script>

And the solution that I'm using was a post here. Again, the msgbox will display fine if I do not have the jQuery UI Dialog open. If I do, then it doesn't display the msgbox and just refreshes the page.

Any ideas?

+5  A: 

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).bind('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    );
</script>
Jordan Ryan Moore
So if I'm returning a string, how do i tell if they said Ok or Cancel? or does it matter? I actually want a confirm('are you an idiot?'); and then capture which result they chose. You have any clue on where I would start on that?
Keith
If they click Cancel, they stay on the page. If they click Ok, they leave the page.
Jordan Ryan Moore
But read my actual issue. This works fine if the jQuery Dialog is not open. If it's open, the confirm does not display and the page just refreshes...
Keith
And to add to my response a bit, you say if they click cancel they stay on the page...with a confirm it's either Yes or No. What's the syntax to keep them on the page if they click yes? And to allow them to navigate back if not?
Keith
For security reasons, the browser doesn't allow you to customize the buttons or the result of the dialog box. In regards to how a jQuery dialog is affecting the unload event, posting the rest of your code would be helpful.
Jordan Ryan Moore
A: 

this works for me

$(window).bind('beforeunload', function() { return 'Do you really want to leave?' ; });

lndr