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">
//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.';
});
}
.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.