Disable AddEventListener On Submit

前端 未结 3 1241
旧时难觅i
旧时难觅i 2021-01-21 11:27

I am trying to disable the function I pass to addEventListener when the user clicks on submit. I put code in to prevent user from leaving page if they have entered

3条回答
  •  清歌不尽
    2021-01-21 12:27

    Was able to solve this problem using the suggestion that was made by Bipperty via this SO issue...Narrow Down BeforeUnload To Only Fire If Field Is Changed or Updated. Ultimately the code below is what I used to turn off beforeunload when submitting the form....

    var submitting = false;
    
    window.addEventListener("beforeunload", function (event) {
      console.log('checking form');
    
      let inputValue = document.querySelector('#myInput').value;
      if(inputValue.length > 0 && submitting === false) {
        console.log(inputValue);
        event.returnValue = 'Are you sure you wish to leave?';
      }
    
      event.preventDefault();
    
    });
    
    document.addEventListener("submit", function(event) { 
      submitting = true;
    });
    

提交回复
热议问题