onbeforeunload - bind to selective events

Neel picture Neel · Mar 27, 2012 · Viewed 12.4k times · Source

I am working on a enterprise application where forms a generated dynamically and we don't have control over the code. Most of the controls in the form have following code associated to them

<select name="s_10_1_1_0"  onchange = 'SWESubmitForm(document.SWEForm10_0,s_5,"","1-E0RHB7")' id='s_10_1_1_0' tabindex=1997 >

<input type="text" name='s_10_1_11_0' value=''  onchange = 'SWESubmitForm(document.SWEForm10_0,s_7,"","1-E0RHB7")' id='s_10_1_11_0' tabindex=1997  maxlength="30">

We would like to present an ok cancel dialog when user tries to navigate to some other page using the link in the header or footer.

I have used to following code to bind onbeforeunload event and present an ok cancel dialog to user.

//this identifies the unique page name
var viewName = $('input[name="SWEView"]').val(); 
// if I am on desired page bind the event so that now dialog is presented to user
 if(viewName == "XRX eCustomer Create Service Request View"){
     $(window).bind('beforeunload', function(){
     return 'Your Inquiry has not been submitted yet.';
});
 }

But the problem is that this dialog comes every time user changes a value of any field in the form (I believe that is due to SWESubmitForm code present for onchange event).

I would like to onbeforeunload dialog to come if user clicks any other link outside form or in other words tie onbeforeunload to selective events (including closing the window) on the page.

Please Help

Answer

jfriend00 picture jfriend00 · Mar 27, 2012

.onbeforeunload() is global. You can't have it trigger for only some ways of leaving the page. If the event handler is installed it will trigger no matter how the viewer is leaving the page.

You can keep track of your own internal state and decide whether to prompt anything in the onbeforeunload() handler or just return nothing (so no prompt is made).

So, you could have code like this:

//this identifies the unique page name
var viewName = $('input[name="SWEView"]').val(); 
// if I am on desired page bind the event so that now dialog is presented to user
if(viewName == "XRX eCustomer Create Service Request View"){
    $(window).bind('beforeunload', function() {
        // figure out whether you need to prompt or not
        if (myStateSaysToPrompt) {
            return 'Your Inquiry has not been submitted yet.';
        } else {
            return;   // no prompt
        } 
   });
}

Update

As this is quite high on google getting many views it would be worth noting that this answer no longer works.

 $(window).bind('beforeunload', function() {

Note that there is no longer 'on' in the event being bound. Using the previous onbeforeunload in later versions of jQuery will result in nothing happening.