tags:

views:

72

answers:

5

I have a several input fields in a form each having a unique name. For example, to change the color I would do:

testForm.username.style.background = "yellow";

username being the name of the input and testform being the form name

I want to do this: replace username with a variable elem so that when I call the function to change the background color I don't need to have a separate function for every unique field. I would just send the elem name and that function would work for every field.

testForm.elem.style.background = "yellow";

My problem is it doesn't work. For example it passed the elem into the function fine, but it says that testForm.elem.style is null. For some reason javascript doesn't like variables for element names I'm guessing?

A: 

You'd have to do an eval to do something like that, eg eval("testform." + elem + ".style.background=yellow");

maxpower47
Don't use `eval()`, it will only give you a headache. Check this out http://www.jslint.com/lint.html#evil
RaYell
+4  A: 
var elem = 'username';
testForm[elem].style.background = 'yellow';
RaYell
Not a good idea. Accessing it off of an `elements` collections would be more reliable and standard-compliant, e.g.: `testForm.elements[elem].style.backgroundColor = 'yellow'`
kangax
RaYell thanks for the help, it worked just like I wanted it to. I was under the impression that testForm[elem].style was the same as testForm.elem.style... guess not!What is the advantage of using the elements collection? How does it help me other than being standard compliant?
payling
I would also test for existence of an element (and its `style` property) before attempting to modify it - `var el = testForm.elements[elem]; if (el `
kangax
A: 

try

testForm [elem].style.background = "yellow";

or

var elem = testForm.username
elem.style.background = "yellow";

in the first case elem holds the username, and in the second case, elem points to the actual DOM element.

Javier
+1  A: 

A property of a JavaScript object (in this case, the "username" property of the object "testform") can be accessed using either object.property or object["property"] syntax. As the second form takes a string (as shown by the double quotes), it follows that a variable containing a string can also be used with that syntax. Hence:

testform[elem].style.background = "yellow";

will do what you want.

NickFitz
A: 

It sounds like you're creating a function to do this anyway. In that case, why not just use the following function:

function changeBackgroundOfElementToYellow(element){
  element.style.background = "yellow";
}

And call it with:

changeBackgroundofElementToYellow(testForm.username);

In general I find the RaYell/kangax method posted already to be better, but this is another option.

Phairoh