1

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

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

5 Comments

You could of course jump straight to the form element with document.getElementsByName('nameOfFormElement')[0].value.
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.
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. :)
Before I began using jQuery, you have no idea how many times' I've made this mistake with document.getElementsByClassName. It took me a while to find that s!
I can definitely empathize with the headache of searching for a string when you've returned an array. Actually, my most notorious trip-up along these lines is attempting to use objects like arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.