简体   繁体   中英

Can't Remove `PreventDefault` Event Listener on Form Submission (JavaScript)

I have a privacy policy checkbox on a form and I've set preventDefault() on the from submission button so the email address isn't submitted unless the checkbox is checked.

In the code below I have a simple removeEventListener method placed on the checkbox for when the checkbox is checked, but the code isn't working?

The preventDefault() method works, but the submission doesn't happen if the privacyCheckbox.checked === true condition is met.

 var mailFormSubmit = document.getElementById('mc-embedded-subscribe'), // subscribe button privacyCheckbox = document.getElementById('privacy-checkbox') // checkbox // prevent default function stopFormSubmit (e) { e.preventDefault() } if (privacyCheckbox.checked === false) { mailFormSubmit.addEventListener('click', stopFormSubmit, false) } if (privacyCheckbox.checked === true) { mailFormSubmit.removeEventListener('click', stopFormSubmit, false) }

The logic you have is just running once, so it will only take care of the initial state of the checkbox. If you want to attach/detach event listeners whenever the checkbox changes , you have to hook up an event listener on your checkbox:

const mailFormSubmit = document.getElementById('mc-embedded-subscribe'),  // subscribe button
      privacyCheckbox = document.getElementById('privacy-checkbox')       // checkbox

function stopFormSubmit (e) {
    e.preventDefault()
}

function updateSubmitBehavior() {
  if (privacyCheckbox.checked) {
    mailFormSubmit.removeEventListener('click', stopFormSubmit, false)
  } else {
    mailFormSubmit.addEventListener('click', stopFormSubmit, false)
  }
}

privacyCheckbox.addEventListener('change', updateSubmitBehavior);

updateSubmitBehavior();

You don't need to removeEventListener simply do like this. Let me assume you are firing

formSumitfunc on form submit event then your function will be

function formSumitfunc(e) {


    if (privacyCheckbox.checked == false) {
        e.preventDefault();

    }

    if (privacyCheckbox.checked == true) {
        // do whatever you want to do.

    } 


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM