Hi, is there a way to validate a form through JS and check how many checkboxes are selected? I have a list with 15 checkboxes and I want that the user check exactly 2 checkboxes.
+2
A:
if( $('input[type="checkbox"]:checked').length == 2 )
{
//good
}
else
{
//bad
}
Alternatively, use
$('myForm :checkbox:checked').length
Stefan Kendall
2009-12-18 22:57:14
can I specify a class for the checkbox?
Pennywise83
2009-12-19 01:36:39
I've solved: $('input[type="checkbox"][name=checkb_name]:checked')
Pennywise83
2009-12-19 01:41:04
A:
var amountOfSelectedCheckboxes = $('input[type=checkbox]:checked').length;
pixeline
2009-12-18 22:58:35
+1
A:
if you don't want to rely on jquery
function exactly2() {
var inputs = document.getElementsByTagName("input");
var count = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count++;
}
}
return (count == 2);
}
lincolnk
2009-12-18 23:06:07
Give a man a bandaid, and he may be able to heal a wound. Give a man a doctor with full medical supplies, and the wound becomes an implementation detail. Not all cuts are solvable with bandaids.
Stefan Kendall
2009-12-18 23:35:51