jQuery Validation for Multiple Checkboxes | PHP Tutorial For Beginners

Sometimes you need to validate a form that has multiple checkboxes and require that at least one is selected. This tutorial shows how to do that with jQuery using serializeArray().

In the example below, clicking Submit calls validate(). If no checkbox is checked, it alerts "nothing selected". Otherwise it reports how many were selected.

Complete Example

<html>
<head>
  <title>jQuery Checkbox Validation</title>
  <script type="text/javascript"
    src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
  <script>
  function validate() {
      var fields = $("input[name='checkbox']").serializeArray();
      if (fields.length == 0) {
          alert('Nothing selected — please choose at least one option.');
      } else {
          alert(fields.length + " item(s) selected.");
      }
  }
  </script>
</head>
<body>
  <form action="" method="GET" id="Form">
    <div>
      <input name="checkbox" type="checkbox" value="PHP Tutorial"> PHP Tutorial
    </div>
    <div>
      <input name="checkbox" type="checkbox" value="Javascript"> JavaScript
    </div>
    <div>
      <input name="checkbox" type="checkbox" value="Validation"> Validation
    </div>
    <br>
    <input name="submit" type="button" value="Submit" onclick="validate();">
  </form>
</body>
</html>

How It Works

  • $("input[name='checkbox']") selects all checkboxes with the name checkbox.
  • .serializeArray() returns an array containing only the checked boxes.
  • If the array length is 0, nothing was checked. Otherwise fields.length tells you how many were selected.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →