C and S Design.
Search Friendly Programming and Design




Code Articles - Javascript

Javascript Select All Checkboxes Checkbox

If you are coding a Web UI (User Interface) for something such as messaging application or a document management, a useful feature to have is the "Select All" checkbox. Where on click will select or deselect all the items displayed on the page. It is a fairly simple feature to code and add to a form.

Example Form

Select All
Box 1
Box 2
Box 3
Box 4
Box 5
Box 6
Box 7
Box 8

The Code

Get this Code: Click to download the Javascript file.

Code for this Example. (Select All Checkboxes)

// Select All checkboxes in form function
function chkAll(name, value) {
// hardcoded form name
	var frm = document.getElementById('testform');
// get all inputs from the form into an array
	var inputs = frm.getElementsByTagName('input');

// loop through the form inputs	
	for (var i=0; i<inputs.length;i++) {
//if the name matches, set the value to match the calling element
		if (inputs[i].name == name) {
			inputs[i].checked = value;
		}
	}
}


Explanation

To go through the code line by line, we have;
function chkAll(name, value) {: Define the function name and declare two parameters
var frm = document.getElementById('testform');: Get the object reference to the form. There are ways that hardcoding can be avoided but for a simple example, this will suffice.
var inputs = frm.getElementsByTagName('input');: Call a DOM method to get the object IDs for all the input elements in the form.
for (var i=0; i<inputs.length;i++) {: This will loop through all the elements in the input array
if (inputs[i].name == name) {: Check if the input name matches the name parameter passed to this function.
inputs[i].checked = value;: If it does, set this elements value to match the value parameter passed
}: Close the for loop.
}: Close the if ... then
}: Close the function

How To Use

<form name="testform" id="testform" method="post" action="">
<input type="checkbox" name="chkall" onclick="chkAll('chk',this.checked)">Select All
<input type="checkbox" name="chk">Box 1
<input type="checkbox" name="chk">Box 2
<input type="checkbox" name="chk">Box 3
<input type="checkbox" name="chk">Box 4
<input type="checkbox" name="chk">Box 5
<input type="checkbox" name="chk">Box 6
<input type="checkbox" name="chk">Box 7
<input type="checkbox" name="chk">Box 8
</form>

Valid HTML 4.01! Valid CSS! copyright © C and S Design 2004 - 2005
Website Design and SE Friendly Coding C and S Design