JS: Unobtrusive Select All Checkboxes
Pete
I wrote last week about how I’m trying to improve my JavaScript skills. As a small exercise I have written this function for unobtrusively selecting/deselecting checkboxes in a form.
JAVASCRIPT:
-
function selectAll(box)
-
{
-
// get the elements name
-
var id = box.id;
-
var name = /^([a-z]+)(_select_all)$/i.exec(id);
-
-
name = name[1];
-
-
re = new RegExp('^'+name+'_[0-9]+$');
-
-
// get the elements stauts
-
var state = box.checked;
-
-
// get the form element, search "up"
-
var form = box.parentNode;
-
while(form.nodeName.toLowerCase() != "form")
-
{
-
if(!form.parentNode) break;
-
form = form.parentNode;
-
}
-
-
// search through forms children for email_ checkboxes
-
for (i=0;i<form.elements.length;i++)
-
{
-
if (form.elements[i].type=='checkbox')
-
{
-
// Find checkbox for each member of the group:
-
if (re.test(form.elements[i].name))
-
{
-
form.elements[i].checked = state;
-
}
-
}
-
}
-
}
-
-
-
-
// onload stuff
-
window.onload = function()
-
{
-
var email = document.getElementById('email_select_all');
-
-
email.onclick = function(){
-
return selectAll(email);
-
};
-
}
The Javascript will work on a HTML form like this
HTML:
-
<form method="post">
-
-
<!-- Select all check box -->
-
<input id="email_select_all" type="checkbox" />
-
-
<!-- list of check boxes -->
-
<input type="checkbox" name="email_1" value="1" />
-
<input type="checkbox" name="email_2" value="1" />
-
<input type="checkbox" name="email_3" value="1" />
-
<input type="checkbox" name="email_4" value="1" />
-
-
<input type="submit" value="Send Message" />
-
</form>
As long at the select all checkbox has an id of "something_select_all" and the checkboxes have id's of "something_"followed by a number then this will work. No inline Javascript is required all the JS can be put in a separate file.
Note: If any Javascript Gurus are reading that have pointers about how I could improve this function then please put your suggestions in the comments.
# Pete Graham
Posted in Tech, javascript, Website Development, unobtrusive |
2 Comments »