8

I am using following JavaScript code to warn a user if he tries to redirect to another page without submitting the form.

window.onbeforeunload = function() {
   return 'Are you sure that you want to leave this page?';
};

This is working fine.But my problem is when user trying to submit the form using submit button confirm box will be appear. I don't want to ask the confirm if user submitting the form,otherwise I want to ask confirm. How is it possible?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
shihabudheen
  • 696
  • 8
  • 26
  • 1
    please check `onbeforeunload`. I think it does not work either in chrome or firefox – Ashwin Jan 31 '13 at 11:48
  • I found as it is working fine with both chrome and Firefox.But both of them responding differently. In my case Firefox asking "This page is asking you to confirm that you want to leave - data you have entered may not be saved." But chrome asking confirm "are you sure to leave the page Are you sure you want to leave this page?" – shihabudheen Jan 31 '13 at 12:02

2 Answers2

10

maintain a state variable. when user click submit button set state to userSubmitted=True;
state variable may include a global variable or hidden control.

var userSubmitted=false;

$('form').submit(function() {
userSubmitted = true;
});

then check like this

window.onbeforeunload = function() {
    if(!userSubmitted)
        return 'Are you sure that you want to leave this page?';
};

PS : cross check for onbeforunload compatibility for cross browser.

Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
2

Simple.

Just have a global variable

var can_leave = false;

on your form:

$('form').submit(function() {
...
...
can_leave = true;
});

And inside your onbeforeunload() handler have this:

window.onbeforeunload = function() {
if (!can_leave)   return 'Are you sure that you want to leave this page?';
};
lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81