Nov 25, 2011

Limit Checkbox amount

Problem: I have 20 Checkboxes. I need to disable 16 Checkboxes, if 4 checkboxes are selected.

Answer: http://jsbin.com/ucuha3/edit#javascript,html

JAVASCRIPT:

$("input:checkbox").click(function() {

var bol = $("input:checkbox:checked").length >= 4;
$("input:checkbox").not(":checked").attr("disabled",bol);

});
HTML:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
1:
2: <meta charset=utf-8 />
3: <title>JS Bin</title>
4: <!--[if IE]>
5: <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
<p id="hello">Hello World</p>
</body>
</html>

No comments: