Sunday, June 3, 2007

Select all

Real world problem from my UI buddy, . The problem - you want to select all the checkboxes inside of a specific div.

Starting out, we can get all the check boxes on a page with getElementsByTagName:


var inputs = document.getElementsByTagName("input");

Note, this will give us all inputs, not just checkboxes. The next step is to loop through the array, find all of the checkboxes, and check them:


for( var i = 0; inputs && i < inputs.length; i++ ){
if( inputs[i].type == "checkbox" )
inputs[i].checked = true;
}


So, wrapping it all up gives us this:

BIGDUMBDEV.selectAll = function(element){
element = this.getElement(element) || document;
if( element && element.getElementsByTagName ){
var inputs = element.getElementsByTagName("input");
for( var i = 0; inputs & i < inputs.length; i++ ){
if( inputs[i].type == "checkbox" )
inputs[i].checked = true;
}
}
}




Note, I wrote my own "getElement" function for this example, you should use the $ function in prototype.js or something similar.

1 comments:

said...

How about making the select link also deselect when clicked again?