[thelist] more loops... this time, javasctipt

Brian Cummiskey Brian at hondaswap.com
Tue Aug 23 11:51:27 CDT 2005

Man, these loops are killing me lately :p  First the asp side yesterday, 
and today, the validation of the form with JS on the front side.  This 
is an intranet application, so its IE6 specifically and i'm the only one 
in the office who knows what web standards are anyway, so the code can 
be "less than up to par" if need be--  just as long as it works.

So, here we go.

I have a form with 28 questions, consisting of multiple answer choice 
radio buttons (acceptable, good, better, excelent, no, n/a) and a 
comments field.

The requirement is, if NO is selected, that the comments blob is a 
required field.

The kicker, is that some questions don't have options for some choices, 
so I can't implicitly say:

   if(theform.q1[4].value == "NO") { ... }

On later questions, the 5th element might not even exist.

Here's the function I came up with, which works:

function valid() {

	var theform = document.getElementById("frmdefault");
	for (i=0; i<theform.q1.length; i++)
		if (theform.q1[i].checked)
			if (theform.q1[i].value == "NO")
				if(theform.q1_comments.value == "")
					alert("Comments required for Q1 when NO is selected");
					return false;


My question is, there's gotta be a better way, than to copy this over 27 
more times for each of the remaining questions, changing q1 to q2, q3, 
and so on up to q28.

Basically, what i need to do is wrap the for loop in another loop, which 
counts from 0 to 27 (or 1 to 28), incrementing the question variable.

If I remember correctly, I need to use the eval() function to evaluate 
'q'+x before i use it as a field label.

Can someone give me a hand getting this started?  I can't seem to find 
anything useful on google.


More information about the thelist mailing list