Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

javascript - Disable AddEventListener On Submit

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 data on any of the fields. This works fine. If the user tries to navigate away they get a warning as expected. However, I can't seem to figure out how to disable this feature once all of the fields are populated and the user clicks submit. As it stands, they are prompted to make sure they want to navigate away when they click on submit and I don't want this to happen when the user clicks submit.

I've tried something like the below, to try to unbind the beforeunload function based on submit, but this isn't working. I feel like this is the right general idea, but I'm struggling to make this work as I want it to.

$('form').submit(function() {
  $(window).unbind('beforeunload');
});

$(window).on('beforeunload',function(){
  return '';
});

The code below works as expected:

window.addEventListener('beforeunload', function (event) {
  console.log('checking form');

  let inputValue = document.querySelector('#myInput').value;

  if (inputValue.length > 0) {
    console.log(inputValue);
    event.returnValue = 'Are you sure you wish to leave?';
  }

  event.preventDefault();
});

If the user clicks submit I want the beforeunload function to be turned off essentially.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...