BrowserMonkey22
BrowserMonkey22

Reputation: 13

Requiring at least 2 check boxes be clicked using JavaScript

I am trying to build a form that requires at least two check boxes to be selected. I have tried everything that I could find without any sort of success.

function cb_require() {
  let chckbx = document.forms['form_name']['contact'].value;

  for (chckbx.length === 1) {
    if (i = 0; i < chckbx.length; i++) {
      alert('check 2');
      return false;
    }
  }
}
<form method="post" name="form_name" id="form_name" action="mailto:[email protected]" enctype="text/plain" onsubmit="return cb_require()">
  <label for="cont">Preferred Contact Method:</label>
  <input type="checkbox" id="Phone" name="contact" value="Phone">
  <label for="Phone">Phone</label>
  <input type="checkbox" id="E-mail" name="contact" value="E-email">
  <label for="E-mail">E-mail</label><br>
  <input type="checkbox" id="Mail" name="contact" value="Mail">
  <label for="Mail">Mail</label>
  <input type="checkbox" id="LinkedIn" name="contact" value="LinkedIn">
  <label for="LinkedIn">LinkedIn</label><br><br>
</form>

Thanks in advance for any help or advice!

Upvotes: 0

Views: 161

Answers (1)

Simone Rossaini
Simone Rossaini

Reputation: 8162

You can simple use querySelectorAll for filter only checkbox checked, if length is equal to two submit form like:

const form = document.querySelector('#form_name');
form.addEventListener('submit', (e) => {
  e.preventDefault();
  let chckboxs = form.querySelectorAll('input[type="checkbox"]:checked');
  if (chckboxs.length > 1) {
    console.log('form submit');
  } else {
    console.log('error form');
  }
});
<form method="post" name="form_name" id="form_name" action="mailto:[email protected]" enctype="text/plain">
  <label for="cont">Preferred Contact Method:</label>
  <input type="checkbox" id="Phone" name="contact" value="Phone">
  <label for="Phone">Phone</label>
  <input type="checkbox" id="E-mail" name="contact" value="E-email">
  <label for="E-mail">E-mail</label><br>
  <input type="checkbox" id="Mail" name="contact" value="Mail">
  <label for="Mail">Mail</label>
  <input type="checkbox" id="LinkedIn" name="contact" value="LinkedIn">
  <label for="LinkedIn">LinkedIn</label><br><br>
  <button type="submit">ClickMe</button>
</form>

Reference:

Upvotes: 1

Related Questions