document.form.variable.value doesnt work-- javascript

Hi all,

I'm trying to construct a variable -> which consists of the element name..like this
str =  ".hdnaccnum"+((frm.name).substr(3));   // returns hdnaccnum15  

Now when i say --- alert(document.frmAvgData+str+".value");       It does'nt work
But when i say  ---- alert(document.frmAvgData.hdnaccnum15.value) ;   // it does work.

How can i construct dynamic variable which refers to an element and get its value
kishan66Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
cyberkiwiConnect With a Mentor Commented:
You can use EVAL but it is evil (use with care)

alert( eval("document.frmAvgData." + str + ".value") )
0
 
kishan66Author Commented:
in the above code ...
str =  ".hdnaccnum"+((frm.name).substr(3));
(frm.name).substr(3) returns the number -- expected value
0
 
kishan66Author Commented:
Thanks cyberkiwi.

It works!!!

But may i ask you why is it kind of Evil? what things should be taken care if i have to use "eval"

0
 
benschwartzConnect With a Mentor Commented:
You can't dynamically form property names in JavaScript, however you can treat JavaScript objects as arrays. Rather then using concatenation to generate a property name, use it to generate an associative array "key". Treat your object as an array and supply your generated key in brackets to get a handle on your property.

alert(document.["frmAvgData" + str].value);
0
 
cyberkiwiCommented:
http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx

and quote from JsLint (an _excellent_ JS resource)
http://www.jslint.com/lint.html
eval is evil
The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.

It is too powerful a feature, so the consensus is that if there are any other alternatives at all, exhaust them all before using eval().  It is necessary for some things though.
0
All Courses

From novice to tech pro — start learning today.