Check all and uncheck all check boxes is a pretty common functionality in web development projects. Previously we used to do this functionality using javascript. In this article I will explain How to implement check all and uncheck all check boxes using jQuery.
We will start with the mark up
HTML
Javascript
Dowonload jquery-1.4.4.min.js
I have created a  "check.js" file into “js†folder. All of our javascript code will go into this javascript file.
We already create the "check.js" file. Â Now we are going to add our javascript into the "check.js" file. Add the following code into check.js file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
$(document).ready(function() {
$('#checkall').click(function(){
$("input[type='checkbox']").attr('checked', $('#checkall').is(':checked'));
//------calculate the value---------
$('form').find(':checkbox').click(function(){
$('div').filter(':gt(0)').find(':checkbox').each(function(){
if($(this).is(':checked'))
amt=amt+parseInt($(this).val());
$(' ').insertAfter('div:eq(5)');
$('p').text('Your bill is $ '+amt);
|
The .attr() method is used for setting the attributes of the selected element(s).
Syntax:
.attr(attribute, value)
The .is() method checks the selected element(s) with a selector and returns true if the any of the selected elements match with the selector; otherwise it returns false.
Syntax:
.is(selector)
The $(#checkall).is(:checked) part of the preceding statement checks if the checkbox of id:checkall is checked. If the checkbox (id: checkall) is checked, the .is() method will return true; otherwise it will return false.
If the .is() method returns true, all the input elements of type:checkbox (that is, all the checkboxes) are set to checked mode; all of them will be set to unchecked mode if the .is() method returns false.
Since the user is allowed to check any individual check box, we check the status of each checkbox that has an index value greater than 0 (because the checkbox with index value 0Â is the Check All checkbox).
The value of all the checkboxes is added to the amt variable. To display the bill, we create a paragraph element and add the text Your bill is amt (where amt is the numerical value contained in the amt variable), and insert this paragraph element after the div element of index value 5; that is, after the last checkbox.
Styling with CSS
1
2
|
body{font-family:Verdana, Geneva, sans-serif; font-size:12px;}
.infobox{ padding: 5px; }
|