/    Sign up×
Community /Pin to ProfileBookmark

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

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@GeatJun 16.2003 — 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.
Copy linkTweet thisAlerts:
@GollumJun 16.2003 — 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;

}
Copy linkTweet thisAlerts:
@scialomauthorJun 16.2003 — 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?
Copy linkTweet thisAlerts:
@GeatJun 16.2003 — 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)
×

Success!

Help @scialom spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...