Select all checkboxes in Javascript dynamically
I was looking at a post entitled Top 10 custom JavaScript functions, and I noticed Dustin talking about the various incarnations of getElementByClass(). I know this function has been around forever, but something triggered in my head and I used it to rewrite the ancient javascript checkbox selector I had (which was not class based). There is nothing original about the rewrite, but there doesn’t seem to be a place to grab something like this off the net if you wanted to avoid writing it by hand.
This was perfect timing because I needed to rewrite the old selector code pretty much immediately.
function checkByClass(checkedClass,checkedStatus,node) {
checkedClass = checkedClass || '*';
checkedStatus = document.getElementById(checkedStatus);
node = (node == null)?document:document.getElementById(node);
var elements = node.getElementsByTagName('input');
var elementCount = elements.length;
var pattern = new RegExp('(^|\\s)'+checkedClass+'(\\s|$)');
for (i = 0, j = 0; i < elementCount; i++) {
if ( elements[i].type == 'checkbox' && pattern.test(elements[i].className) ) {
elements[i].checked = checkedStatus.checked;
}
}
}
The code will make checks based on a class, and a controlling checkbox. As with the original code, you can even manipulate checkboxes within a given element. You can see the bland demo page here. Many thanks to Dustin for causing my last two neurons to fire and give me some incentive to throw out old code






September 20th, 2008 at 2:36 pm
Great script! I love the ability to check all by class or by existence in a specific div/node. Very helpful!