Click to See Complete Forum and Search --> : Loop


scialom
06-16-2003, 08:19 AM
Hi I have this code:

var Lig1 = window.document.step4.light1;
if (Lig1.checked==true){
window.document.step4.light.value=1;
}
var Lig2 = window.document.step4.light2;
if (Lig2.checked==true){
window.document.step4.light.value=2;
}
var Lig3 = window.document.step4.light3;
if (Lig3.checked==true){
window.document.step4.light.value=3;
}

I want to do it with a loop.
I do it like this:
for (var y=1;y<4;y++){
var Lig+"y" = window.document.step4.light+"y";
}

It is not working. What should I do?

thanks,
Assaf

Geat
06-16-2003, 08:28 AM
The Eval() function takes a string and evaluates it as if it were a line of Javascript code. Therefore:

for (var y=1;y<4;y++){
eval("Lig"+ y + "= window.document.step4.light" + y);
}

Will have the desired effect.

Gollum
06-16-2003, 08:30 AM
try this...

for ( var y = 1; y < 4; y++ )
{
var lig = window.document.step4['light' + y];
if ( lig.checked ) window.document.step4.light.value=y;
}

scialom
06-16-2003, 08:58 AM
I try it like this:
for ( var y = 1; y < 5; y++ )
{
eval("Lig"+ y + "= window.document.step4.light" + y);
if (eval("Lig"+y.checked==true)){
window.document.step4.light.value=y;
(window.document.step4.light.value);
}

}

the first eval is working just fine, but with the if statment it doesnt. why?

Geat
06-16-2003, 09:01 AM
by saying "if(eval..." you're simply checking whether or not the eval method succeeded (remember that it is a method and so returns a result of it's own.

You need to put the whole if statement within the eval:

eval("if (Lig" + y + " .checked==true)) { window.document.step4.light.value=" + y + ";
(window.document.step4.light.value);
}");

(All on one line)