Categories
JavaScript Answers jQuery

How to Validate that a Form with Multiple Checkboxes to Have at Least One Checked with jQuery?

Spread the love

To validate that a form with multiple checkboxes to have at least one checked with jQuery, we can call the serializeArray method on the selected checkboxes to see how many of them are checked.

For instance, if we have the following form:

<form>
  <fieldset id="cbgroup">
    <div><input name="list" id="list0" type="checkbox" value="newsletter0">zero</div>
    <div><input name="list" id="list1" type="checkbox" value="newsletter1">one</div>
    <div><input name="list" id="list2" type="checkbox" value="newsletter2">two</div>
  </fieldset>

  <input name="submit" type="submit" value="submit">
</form>

Then we can check how many checkboxes are checked by writing:

const onSubmit = (e) => {
  e.preventDefault()
  const fields = $("input[name='list']").serializeArray();
  if (fields.length === 0) {
    console.log('nothing selected');
    return false;
  } else {
    console.log(fields.length, "items selected");
  }
}

document.forms[0].addEventListener('submit', onSubmit)

We have the onSubmit function that’s used as the submit handler of the form.

In the function, we call e.preventDefault to prevent the server-side submission behavior.

Then we call $("input[name='list']").serializeArray() to return an array of checked checkboxes and assign it to fields.

Therefore, if fields.length is 0, then nothing is checked.

Otherwise, at least some checkboxes are checked.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *