Jquery counts the number of checkboxes selected by users
- 2020-03-30 03:13:48
- OfStack
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery test</title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<input type="checkbox" name="check" value="one"/>one<br/>
<input type="checkbox" name="check" value="two"/>two<br/>
<input type="checkbox" name="check" value="three"/>three<br/>
<input type="checkbox" name="check" value="four"/>four<br/>
<input type="checkbox" name="check" value="five"/>five<br/>
<input type="checkbox" name="check" value="six"/>six<br/>
<input type="checkbox" name="check" value="seven"/>seven<br/>
<button name="sub"> submit </button>
<script type="text/javascript">
$("button[name=sub]").click(function(){
var len = $("input:checkbox:checked").length;
alert(" You've chosen all of them "+len+" A check box ");
})
</script>
</body>
</html>
Use the selector to get the collection of all checked check box elements, and then determine the number of elements to get the number of checks the user has checked.
Sometimes, we also set a limit on the number of checkboxes that the user can check. If only three checkboxes can be checked, the corresponding code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery test</title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<input type="checkbox" name="check" value="one"/>one<br/>
<input type="checkbox" name="check" value="two"/>two<br/>
<input type="checkbox" name="check" value="three"/>three<br/>
<input type="checkbox" name="check" value="four"/>four<br/>
<input type="checkbox" name="check" value="five"/>five<br/>
<input type="checkbox" name="check" value="six"/>six<br/>
<input type="checkbox" name="check" value="seven"/>seven<br/>
<script type="text/javascript">
$("input:checkbox").click(function(){
var len = $("input:checkbox:checked").length;
if(len>3){
alert(' Honey, you can only choose three at most ~');
return false; //Cancel the one you just checked
}
})
</script>
</body>
</html>