Home > OS >  How come my simple checkbox form is not completing its action upon submitting
How come my simple checkbox form is not completing its action upon submitting

Time:07-02

Its a simple form with a action that should go to the "nextPage.html". it only has 1 input which is a checkbox and a submit button.

const form = document.getElementById('form')
const checkbox = document.getElementById('checkbox')
const message = document.getElementById('message')

form.addEventListener('submit', function validateCheckbox(e) {
    e.preventDefault()
    if (checkbox.checked === true) {
        message.innerHTML = 'Done'
    }
    else {
        message.innerHTML = 'Please check the box to continue!'
    }
})
 <div >
                <form method="post" action="nextPage.html" id="form">
                    <label for="checkbox">By continuing, I agree that I have read and understand the terms of service.</label> <br>
                    <input type="checkbox" id="checkbox">
                    <button type="submit">Submit</button>
                    <h5 id="message"></h5>
                </form>
                    
            </div>

CodePudding user response:

e.currentTarget.submit(); will "manually" submit the form after you've verified that the checkbox is checked. Also side-note, it is always recommended to include semicolon line terminations.

const form = document.getElementById('form');
const checkbox = document.getElementById('checkbox');
const message = document.getElementById('message');

form.addEventListener('submit', function validateCheckbox(e) {
  e.preventDefault();
  if (checkbox.checked === true) {
    message.innerHTML = 'Done';
    e.currentTarget.submit();
  } else {
    message.innerHTML = 'Please check the box to continue!';
  }
})
<div >
  <form method="post" action="nextPage.html" id="form">
    <label for="checkbox">By continuing, I agree that I have read and understand the terms of service.</label> <br>
    <input type="checkbox" id="checkbox">
    <button type="submit">Submit</button>
    <h5 id="message"></h5>
  </form>
</div>

  • Related