views:

86

answers:

4

I have some javascript code to alert the user that leaving the page will lose the answers to form questions.

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

I'd like to make this happen for everything BUT a form submission.

My submit button has the ID #submit and I am using the prototype framework.

So something like: if $("submit") clicked then skip function call?

I am still pretty new to JS/Prototype so I'm not exactly sure how to approach this.

+1  A: 

You could unbind the event just before the form submission:

document.getElementById('formId').onsubmit = function () {
  window.onbeforeunload = null;
};
CMS
A: 

You can only call window.onbeforeunload = askConfirm; when user has started entering text into your fields.

As for your submission, you can do it at the form tag:

<form action="controller.php" onsubmit="window.onbeforeunload = function(){}" method="post">

This will remove the pop up when the user is submitting the form.

thephpdeveloper
+2  A: 

I would add an onclick event to the button. The event sets a global variable to true (e.g. dont_confirm_now). If the flag is set to true, do not return anything. Remember to reset the variable immediately in case the user cancels loading of the next page.

Pekka
I like the variable approach a lot since you can init the variable as false and toggle it to true only if the user modifies something on the page.
Chris Pebble
+4  A: 

I would suggest using a global variable for this because you may want cancel the confirmation if the user made no changes to the form. Like on SO if you start typing an answer and try to navigate away you are prompted to confirm, but if you do not start typing you are not prompted.

Create a global variable. On each form field the blur event can set the variable if changes were made. The askConfirm function can check the variable before prompting.

Vincent Ramdhanie