We help IT Professionals succeed at work.

not able to loop over checboxes

-Dman100-
-Dman100- used Ask the Experts™
on
I am trying to loop over a number of checkboxes in an array, but for some reason, I'm not entering the loop?

See my code below.
function validate(){
		var flag = true;
		var container = document.getElementById("inputContainer");
		var ckbxContainer = document.getElementById("checkboxContainer");
		var firstnameErrMsg = document.getElementById('fnameErrMsg');
		var lastnameErrMsg = document.getElementById('lnameErrMsg');
		var emailErrMsg = document.getElementById('emailErrMsg');
		var inputs = container.getElementsByTagName("input");
		var checkboxes = ckbxContainer.getElementsByTagName("checkbox");
		
		for (var i = 0; i < checkboxes.length; i++){
			alert("We are here");
			alert(checkboxes[i].value);
		}
		
		for(var i = 0; i < inputs.length; i++){
			var str = inputs[i].name;
			if (str.indexOf('fname') != -1) {
				if (inputs[i].value == "") {
					firstnameErrMsg.style.display='block';
            		flag = false;
				}	
				else {
					firstnameErrMsg.style.display='none';
				}		
			}
			if (str.indexOf('lname') != -1) {
				if (inputs[i].value == "") {
					lastnameErrMsg.style.display='block';
            		flag = false;
				}	
				else {
					lastnameErrMsg.style.display='none';
				}		
			}
			if (str.indexOf('email') != -1) {
				if (inputs[i].value == "") {
					emailErrMsg.style.display='block';
            		flag = false;
				}
             	else {
                	emailErrMsg.style.display='none';
             	}			
			}
		}	
		if(flag == false){
			return flag;
		}else{
			return flag;
		}
	}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
There wont be any elements returned by getElementsByTagName("checkboxes").

You have to use inputs, with a condition as shown..

for (var i = 0; i < inputs.length; i++){
   if(inputs[i].type == 'checkbox'){
			alert("We are here");
			alert(inputs[i].value);
   }
}

Open in new window

Multitechnician
Top Expert 2014
Commented:
var checkboxes = ckbxContainer.getElementsByTagName("checkbox");

By Tag Name : checkbox
There's no checkbox tag but INPUT

So you need to check the type of your input inside your loop

for(var i = 0; i < inputs.length; i++){
   if( inputs.type == "checkbox") {

Open in new window


leakim971Multitechnician
Top Expert 2014

Commented:
thanks I think you fix my mistake line two :

if( inputs[i].type == "checkbox") {

Open in new window