views:

249

answers:

2

I have some simple code to display a confirm dialog box when the user tries to leave my form:

window.onbeforeunload = askConfirm;
function askConfirm(){
    return "Your answers will be lost.";
}

But this is a multi-page form and they frequently press back to change some values on a previous page.

But when they do this dialog box still comes up.

Is there a way around this?

+1  A: 

I don't see a way to specifically detect whether the user pressed "back" or any other browser button. This is outside the site's scope.

Only one solution comes to mind: Show the confirmation dialog only when a global flag has been set to "true".

if (ask_when_exiting == true)
 return "Your answers will be lost.";

You would have to set the variable to true? in the onclick event of every link that you want the confirmation to pop up for. You should be able to mass apply this event to every link on your page using JQuery or another JS framework (Seomthing like $$('a').each()....).

However, this will disable the confirmation for reloading the page, or any other event that is not triggered using a control on the page like typing in another URL or closing the browser, as well.

Pekka
And of course (as you allude to) this won't work for 1) a user typing in a new address and leaving your site, or 2) a user closing their browser.
JacobM
Yes. Added your examples to the answer.
Pekka
+2  A: 

The answer I would suggest unfortunately doesn't actually answer your question but is a solution of a kind. The only possible solution here, imv, is to make sure that a user clicking the back button doesn't actually create an issue by storing the form answers from all pages. In the case of PHP I would store them in a session ($_SESSION). You have to recognise that users use the back button more than any other UI element within a browser. If your form truly has to be across a number of pages then you need to make sure the data they have entered is persistent across all these pages. I would actually provide a navigation for this within your own interface. Provide a clear sequential process visually and allow instant navigation through this process where possible.

seengee