up vote 0 down vote favorite
share [g+] share [fb]

I have a two variables. One containing the value of the `name` attribute of an input element, and another containing the value of the name attribute of its form element.

Using JavaScript how do I reference that input element just like below, except for replacing the inputname with the value of the variable that contains the name attribute of the input element, and the formname with the value of the variable that contains the name attribute of the form element?

document.formname.inputname


I don't mean to sound complicated, and I am looking forward to a reply,

-An inquisitive Web Developer

link|improve this question

77% accept rate
feedback

1 Answer

up vote 4 down vote accepted

Hmm, I think you could just use this:

document.forms['nameOfForm']['nameOfFormElement'];

And to get the value of the elements, just append .value to the end:

document.forms['nameOfForm']['nameOfFormElement'].value;
link|improve this answer
1  
You could of course jump straight to the form element with document.getElementsByName('nameOfFormElement')[0].value. – 65Fbef05 Apr 14 '11 at 15:40
1  
Notice that getElementsByName has an s in it, which makes it plural, so it's an array. You'd have to do document.getElementsByName('nameOfFormElement')[0].value to make it work properly, as name isn't unique. – Blender Apr 14 '11 at 15:42
Excellent, Thank you Guys! – Web_Designer Apr 14 '11 at 15:43
You're welcome. – Blender Apr 14 '11 at 15:45
Good catch @Blender. I know how to use the function but apparently I don't know how to proof-read my comments before I submit them. :) – 65Fbef05 Apr 14 '11 at 15:46
show 2 more comments
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.