Javascript Function to Check or Uncheck all Checkboxes

Javascript Function to Check or Uncheck all Checkboxes

This Javascript function will check or uncheck all the checkboxes in an HTML form.

This function is specially designed for dynamic pages with varying numbers of checkboxes. Unlike other functions out there, it will work without error even if there are no checkboxes or there is only one checkbox. It is also significantly faster for long lists, because it saves the length of the checkbox in a variable, instead of recalculating it in the loop. Finally, the function is granted to the public domain–use it as you wish.

Instructions

Provide the form name and the field name of the checkbox as the parameters to the function. Then specify true or false as the CheckValue, depending on if you want to check or uncheck all the checkboxes, respectively. The function simply returns without doing anything if the checkboxes do not exist, so make sure you enter the correct FormName and FieldName. Remember, unlike HTML, Javascript form and field names are case-sensitive!

JavaScript Source Code


function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}


Example http://www.somacon.com/p117.php

Leave a comment