Dont ask confirm if user submit the form

谁都会走 提交于 2019-11-30 03:50:08

问题


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?


回答1:


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.




回答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?';
};


来源:https://stackoverflow.com/questions/14624843/dont-ask-confirm-if-user-submit-the-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!