Dont ask confirm if user submit the form

前端 未结 2 386
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 01:02

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() {         


        
相关标签:
2条回答
  • 2021-01-05 01:21

    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.

    0 讨论(0)
  • 2021-01-05 01:32

    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?';
    };
    
    0 讨论(0)
提交回复
热议问题