PDA

View Full Version : DOM arrays and foreach loop


darren-w
08-27-2009, 03:40 PM
Hi,

I would like to run a foreach loop for DOM elements and substitute in vars from an array, here is an example of the concept

//this checks if a box is checked and alerts if it is...

var testItem=array("item1","frog","bone")

for (i in testItem)
{
if (document.form.testItem[i].checked) alert("is checked");
}

I think I am missing out something really fundamental here I've tried appending with + eg "document.form.+testItem[i]+.checked" but this is wrong.

Can this be done?

Darren

A1ien51
08-27-2009, 07:36 PM
The syntax is

document.forms["formName"].elements["elementName"]
OR
document.formName.elements["elementName"]

I am not sure what you are trying to do there with your syntax.

Eric

Kor
08-28-2009, 10:40 AM
Could be also:

var testItem=["item1","frog","bone"], name, i=0;
while(name=testIdem[i++]){
if (document.getElementsByName(name)[0].checked){alert(name+" is checked");};
}