-2

I need to show an error if none of the below checkboxes are checked using using JavaScript.

<tr>
  <td>Status</td>
  <td colspan="3">
    <input type="checkbox" name="chk_stat[]" value="single" id="chk_stat">single

    <input type="checkbox" name="chk_stat[]" value="married" id="chk_stat">Married

    <input type="checkbox" name="chk_stat[]" value="divorcee" id="chk_stat">Divorcee

    <input type="checkbox" name="chk_stat[]" value="student" id="chk_stat">Student
  </td>
</tr>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Dew Drop
  • 71
  • 1
  • 11

1 Answers1

2

You can implement it using selecting all elements with some given name using document.querySelectorAll and an attribute selector using the pseudoclass :checked:

var checkedCheckboxes = document.querySelectorAll("[name='chk_stat[]']:checked");

if (checkedCheckboxes.length == 0) {
  console.log("No checkbox is checked...");
}
<tr>
  <td>Status</td>
  <td colspan="3">
    <input type="checkbox" name="chk_stat[]" value="single" id="chk_stat">single

    <input type="checkbox" name="chk_stat[]" value="married" id="chk_stat">Married

    <input type="checkbox" name="chk_stat[]" value="divorcee" id="chk_stat">Divorcee

    <input type="checkbox" name="chk_stat[]" value="student" id="chk_stat">Student
  </td>
</tr>
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206