1

I have a table and I need to show an alert if no check box is selected.

Below is the table structure

<table id="mytable">
  <tr><td><input type="checkbox" name="one" value="1" /></td></tr>
  <tr><td><input type="checkbox" name="two" value="2" /></td></tr>
  <tr><td><input type="checkbox" name="three" value="3" /></td></tr>
</table>

Please guide me how can I achieve this?

Rich Turner
  • 10,800
  • 1
  • 51
  • 68
user2168066
  • 627
  • 11
  • 21
  • Duplicate 1:http://stackoverflow.com/questions/4086957/jquery-see-if-any-or-no-checkboxes-are-selected Duplicate 2: http://stackoverflow.com/questions/2684434/jquery-check-if-at-least-one-checkbox-is-checked Plz check these two links – Bacteria May 06 '15 at 21:41

3 Answers3

4

To check how many checkboxes are checked, you can simply use:

var checked = $('#mytable').find(':checked').length;

This counts how many checked elements there are within your #mytable element. If this returns 0 then we know that none are checked, so we can display the alert:

if (!checked)
    alert('...');

Demo

$('button').on('click', function() {
  var checked = $('#mytable').find(':checked').length;

  if (!checked)
    alert('No checkboxes are checked!');
  else
    alert(checked + ' checkboxes are checked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="mytable">
    <tr><td><input type="checkbox" name="one" value="1" /></td></tr>
    <tr><td><input type="checkbox" name="two" value="2" /></td></tr>
    <tr><td><input type="checkbox" name="three" value="3" /></td></tr>
</table>

<button type="button">Check</button>
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

This would do the trick

if ($('#mytable :checked').length == 0) {
     // no checkbox is selected, show your validation message
     return
}

// at least one checkbox is checked, continue with normal flow
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

Both the vanilla JS document.querySelectorAll("#mytable input:checked").length and the jQuery $(#mytable :checked).length should do the trick.

document.getElementById("submit").onclick = function() {
  var count = document.querySelectorAll("#mytable :checked").length;
  document.getElementById("output").innerHTML = count;
};
<table id="mytable">
  <tr>
    <td>
      <input type="checkbox" name="one" value="1" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name="two" value="2" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name="three" value="3" />
    </td>
  </tr>
</table>
<input id="submit" type="button" value="count checks" />
<div id="output" />
Thriggle
  • 7,009
  • 2
  • 26
  • 37