Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dont ask confirm if user submit the form

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?

like image 787
shihabudheen Avatar asked Jan 31 '13 11:01

shihabudheen


1 Answers

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.

like image 83
Ravi Gadag Avatar answered Oct 30 '22 20:10

Ravi Gadag