Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through Checkboxes

Status
Not open for further replies.

HisMightiness

Programmer
Mar 17, 2004
54
US
I have a script where I return true if any checkboxes are checked. However, it only works in IE. Firefox throws an error on the For loop line. It says that "col has no properties".

How can I ammend this to make it cross-browser compatible?

Here is the snippet:

function areAttractionCheckboxesSelected(){
var ctrl = document.getElementById('checkboxname');
var col = ctrl.all;

for (i = 0; i < col.length; i++){
if (col.tagName.toUpperCase() == 'INPUT'){
if(col.checked){
return true;
}
}
}
return false;
}

Will
 
You've probably used sloppy "IE-only" HTML code, and given your checkboxes names, but used the "ID" methods to get references to them.

Assuming that is the case, then instead of using this:

Code:
var ctrl = document.getElementById('checkboxname');
var col = ctrl.all;

try this:

Code:
var col = document.forms['yourFormName'].elements['checkboxname'];

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Here is the method I have just found that works in both IE and Firefox:

Code:
    var ctrl = document.getElementById('CheckboxContainerID');
	var col = ctrl.getElementsByTagName('input');
	
	for (i = 0; i < col.length; i++){
	    if (col[i].tagName.toUpperCase() == 'INPUT'){
	        if(col[i].checked){
	            return true;
	        }
	    }
	}
	return false;

Will
 
There are additional elements, but they are table elements that are dynamically generated at run-time. The IDs should be unique. However, I would imagine that the names are not. I have not checked since it began working, sorry. :)

Will
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top