Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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:bb@yahoo.com" 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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:bb@yahoo.com" 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:

  • *.querySelectorAll()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!