Check all checkboxes using Javascript with jQuery

So I had a form with a bunch of checkboxes and I needed to make a checkbox that would check all of them at once. In comes jQuery to the rescue to make this nice and simple.

So here is our javascript function:

function checkAll( form_id, checkall_id ) {
	
	if ($("#" + checkall_id).val() == 1) {
		$("form#" + form_id + " INPUT[type='checkbox']").attr('checked', false);
		$("#" + checkall_id).val(0);
	} else {
		$("form#" + form_id + " INPUT[type='checkbox']").attr('checked', true);
		$("#" + checkall_id).val(1);
	}
}

And here is our check all checkbox in our form:


So lets break down what this does. ‘form_id’ is the id attribute of my form tag. ‘checkall’ is the id of my check all checkbox. When we click the check all checkbox it fires the onclick event which calls the checkAll function. This function receive the id of our form (form_id) and check all button (checkall). Now we look at the value of our checkall button and either turn on or turn off all the checkboxes in that form. We then flip the value of the checkall button so it does the opposite the next time we click it. jQuery does all the work for us.

Pretty simple.

[carousel keywords=”javascript, jquery” category=”Books” tag=”damnsemi01-20″ showBorder=”True”]

Continue Reading