kush
kush

Reputation: 16928

Javascript message to confirm when exiting a form

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.

Upvotes: 0

Views: 584

Answers (3)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

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.

Upvotes: 4

Pekka
Pekka

Reputation: 449753

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.

Upvotes: 2

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827862

You could unbind the event just before the form submission:

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

Upvotes: 1

Related Questions