Form check with JS: select at least one checkbox and max 2 checkboxes
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开发者_JAVA技巧 that the user check exactly 2 checkboxes.
if( $('input[type="checkbox"]:checked').length == 2 )
{
//good
}
else
{
//bad
}
Alternatively, use
$('myForm :checkbox:checked').length
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);
}
var amountOfSelectedCheckboxes = $('input[type=checkbox]:checked').length;
精彩评论