Somacon.com: Articles on websites & etc.

§ Home > Index > Web Development

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

Use your browser's view source command to see how the buttons below work to select or unselect all the checkboxes. Also note how we used the HTML label tag to make the whole text clickable. Everybody should use labels because clicking on the text is much easier for people than clicking on a small checkbox.




  

Have you heard of the new, free Automated Feeds offered by Google Merchant Center? Learn more in Aten Software's latest blog post comparing them to traditional data feed files.
Created 2004-12-13, Last Modified 2011-07-24, © Shailesh N. Humbad
Disclaimer: This content is provided as-is. The information may be incorrect.