Dynamically assign value to hidden fields?

B

Brad Melendy

Hello,
I have a function that among other things, assigns a value to a hidden
field element. However, I want to pass the name of a hidden field to
my function and then assign it a value. So instead of this:

document.forms[0].elements[4].value = "this is a test";

I want to be able to do something like this:

document.forms[0].+MyVarName+.value = "this is a test";

Where MyVarName is the name of the field at position 4 in the array of
form elements.

Does anyone know if this is possible? When I try to do this I
generate an error. Thanks for any help!

....Brad
 
V

Vjekoslav Begovic

You can do that using eval() function, e.g.

function assignValue(MyVarName){
str = "document.forms[0]."+MyVarName+".value = 'this is a test'";
eval(str);
}

but you should consider using DOM, something like this

document.getElementById(MyVarName).value = "test"
 
L

Lasse Reichstein Nielsen

Vjekoslav Begovic said:
You can do that using eval() function, e.g.

function assignValue(MyVarName){
str = "document.forms[0]."+MyVarName+".value = 'this is a test'";
eval(str);
}

You *never* need eval to access properties. This can be written
without eval as:
document.forms[0][MyVarName].value = "this is a test";
or even better:
document.forms[0].elements[MyVarName].value = "this is a test";
but you should consider using DOM, something like this

document.getElementById(MyVarName).value = "test"

"document.forms" is just as legal DOM as "document.getElementById".

/L 'please don't top post'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top