Skip to content
Advertisement

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

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 class="container">
                <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>

Advertisement

Answer

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 class="container">
  <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>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement