Description:
This script only needs your form id. And then it checks or unchecks all the checkboxes inside it based on if the main ’select / unselect all’ checkbox is ticked or not.
Javascript:
<script language=”javascript” type=”text/javascript”>
function selectall(formid,checkboxdompath) {
var formdompath= document.getElementById(formid); /* dom path to your form via the form’s id */
for (i=0; i<formdompath.elements.length; i++){ /* a loop that goes trough all the elements of your form via it’s dom tree. ‘formdompath.elements.length’ tells it how many input elements the form contains, i.e. to which number it should increment to before it terminates */
formdompath.elements[i].checked=checkboxdompath.checked?true:false; /* this is a shorthand if/else statement that first sees if the main box is checked or unchecked, and then it copies that checked or unchecked state to all other boxes */
}
}
</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:
- Place the ’select all’ box outside the form tags of the form whose boxes you wish to select/unselect
- 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 being a dumbass on that one.