Check / Select All checkboxes with javascript

Description:

‘select / unselect all’ checkbox that does it to all checkboxes in a form via its ID.

Javascript:

<script language=”javascript” type=”text/javascript”>

function selectall(formid,selectallcheckbox)
{/* dom path to your form via the form’s id */
var formdompath= document.getElementById(formid);
/* ‘formdompath.elements.length’ tells it how many input elements the form contains, so as long as ‘i’ is less than it, it will continue looping, trough the array of elements */
for (i=0; i<formdompath.elements.length; i++)
{/* if/else statement that first sees if the ‘select all’ checkbox is checked or unchecked, and then it copies that checked or unchecked state to all other boxes */
if(selectallcheckbox.checked = true)
{
formdompath.elements[i].checked = true;
{
else if (selectallcheckbox.checked = false)
{
formdompath.elements[i].checked = false;
}
}
}
</script>

XHTML:

<form id=”myformid”>

<input type=”checkbox” name=”1″ value =”1″ />1<br />

<input type=”checkbox” name=”2″ value =”2″ />2<br />

<input type=”checkbox” name=”3″ value =”3″ />3<br />

<input type=”checkbox” name=”4″ value =”4″ />4<br />

</form>

 

<input type=”checkbox” name=”selectall” onclick=”javascript:selectall(‘myformid’,this);” />

Please note, to make this work, you should:

  1. Place the ‘select all’ box outside the form tags of the form whose boxes you wish to select/unselect
  2. Place the internal Javascript  / link to external Javascript file into the footer of the page. So it works in Firefox. I think it has something to do with the way Firefox loads file i.e. bottom to top. Please correct me if I’m wrong on that one.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s