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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
cyberkiwiCommented:
You can use EVAL but it is evil (use with care)

alert( eval("document.frmAvgData." + str + ".value") )
0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
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
 
benschwartzCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.