[thelist] help me compress this JS function?

Kae Verens kverens at contactjuggling.org
Fri Mar 28 03:04:02 CST 2003


Tom Dell'Aringa wrote:
> ========================
> function toggleAllCheckboxes(oForm, cbGroup, button)
> {
> 	var len = oForm.length;
> 	for(i=0;i<len;i++)
> 	{
> 		currentElement = oForm.elements[i];
> 		if(oForm.elements[i].type == "checkbox")
> 		{
> 			var matchGroup = currentElement.value.substring(0,4);
> 			if(matchGroup == cbGroup)
> 			{
> 				if(currentElement.checked == true)
> 				{
> 					currentElement.checked = false;
> 					button.value = "Select All";
> 				}
> 				else
> 				{
> 					currentElement.checked = true;
> 					button.value = "Deselect All";
> 				}
> 			}
> 		}
> 	}
> }
> ========================
> 
> There can be 2 or 3 groups of buttons like this on a page, which is
> why I am doing the substring thing. I only need to name my CB groups
> like "cbg1_somevalue" or "cbg2_anothervalue" to keep them distinct.
> 
> One thing I wanted to do was use a tertiary operator for the if then
> else..but couldn't get it to work. This is what I tried: (pseudo)
> 
> if(matchGroup == cbGroup) ? uncheck boxes : check boxes
> 
> This throws a syntax error.. it seems to follow the right syntax but
> obviously not. I don't have my Danny G book on me so I am lost :P

the ternary operator is used wrong here. should be be like this:
variable=(match criteria)?'true answer':'false answer';

here's my first pass at the above, although I would approach the problem 
differently myself, I think.

========================
function toggleAllCheckboxes(oForm, cbGroup, button){
   for(i=0;oForm[i];i++){
     currentElement = oForm.elements[i];
     if(currentElement.type=="checkbox"&&
       currentElement.value.substring(0,4) == cbGroup){
       currentElement.checked=(currentElement.checked)?false:true;
       button.value=(currentElement.checked)?'Deselect All':'Select All';
     }
   }
}
========================

further optimization might be to group your elements using the 
<fieldset> element, and run your function based on it's contents - and 
not the entire form.

I haven't tested the above, but it's just a compressed version of your 
own, so shouldn't be too buggy.

-- 
Kae  Verens +----------------------------------+ webworks.ie
        pay  |      http://www.webworks.ie      |  bee
    play     |  http://www.contactjuggling.org  |     boss
kae         |http://kverens.contactjuggling.org|         god



More information about the thelist mailing list