JQuery Form Checkboxes

I was looking at Newegg‘s checkout procedure and it had this cool check box where you could either check all or check none, and then when you clicked on a sub checkbox it would check or uncheck the check all checkbox if it didn’t meet that condition. I re-created the code in JQuery so I could use it on one of my projects.

The HTML markup:

Title
Trinity Mobile Bin Rack
Trinity Stainless Steel Work Table
Trinity NSF 5-Tier XL Heavy-Duty Commercial Chrome Shelving Rack

Ok, if you look at the markup, you’ll see that the table header has a checkbox with the id of ‘chkAll’. Then for all the items I have them with the class ‘chkbox’. It is important to note that the chkAll checkbox does NOT have the class ‘chkbox’.

The JQuery code:

 $(document).ready(function()
        {
			$("#chkAll").click(function()
			{
				var flag = $(this).is(':checked');
				$('input.chkbox').attr('checked',flag);
			});
			$('input.chkbox').click(function()
			{	
				var flag = true;
				$('input.chkbox').each(function()
				{
					flag = flag && $(this).is(':checked');
				});
				$("#chkAll").attr('checked',flag);
			});
        });

So how does it work? I make sure to call the functions only when the document is ready. Once that happens I attach a function to the clicking of the id ‘chkAll’. In this function I first check to see if the current chkAll checkbox is checked or not, if it is then I’m going to immediately make all the class ‘chkbox’ checkboxes to checked and vice versa.

The second function I have is if I happen to click one of the class ‘chkbox’ checkboxes, Again I attach a function to the click event. I use a JQuery expression .each- which is kinda like a foreach loop, which will loop through all the elements that satisfy my ‘chkbox’ class, I then create a variable that AND’s all the other element’s states. When it is done, I am able to determine if the chkAll checkbox should be checked or not.

See the demo

Leave a Reply