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?
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?
Share edited May 6, 2015 at 22:04 Rich Turner 11k1 gold badge53 silver badges68 bronze badges asked May 6, 2015 at 21:29 user2168066user2168066 63512 silver badges21 bronze badges 1- Duplicate 1:stackoverflow./questions/4086957/… Duplicate 2: stackoverflow./questions/2684434/… Plz check these two links – Bacteria Commented May 6, 2015 at 21:41
3 Answers
Reset to default 4To 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./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>
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
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" />