Disable AddEventListener On Submit

前端 未结 3 1345
旧时难觅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:03

    If you bind a handler using .on() you can remove the bound event using .off()

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

    However, I feel in your scenario you don't really need the beforeunload at all if you handle your form submit logically.

    I've mocked up an example of how you can logically submit the form if a user chooses to submit the form based on a condition (in this case if all fields aren't filled).

    $('form').on('submit', function (e) {
      var inputs = $(':text', this);
      console.log(inputs.length)
      var validInputs = inputs.filter(function () {
        return $(this).val().length;
      }).length;
      if (validInputs > 0 && validInputs < inputs.length) {
        var r = confirm("Are you sure you want to leave?");
        if (!r) e.preventDefault()
      }
    })
    
    
    

提交回复
热议问题