Thursday, June 7, 2007

Select all, part 2

A suggestion from the last post - make the select all toggle the results. Sounds good to me. The functionality of the link will be:
if all the boxes are checked, then uncheck all of them, else check all the boxes.

We can extend the previous code to first determine whether we'll be checking or unchecking:


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

Then, use the checked variable in the lower loop. The final code looks like this:

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

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


0 comments: