3

Here's the form:

<form name=fname ...
   <input name=iname value="" ...

This javascript function obtains the value of the input with:

var val = document.fname.iname.value;

Is that legit? I thought you had to do this with getElementsByName. It works, it's just I've never seen anyone do it that way. Is this one of those things that just happens to work... for now?

3
  • yes you can do this with the name attribute. Commented Dec 11, 2016 at 23:19
  • document.forms.fname.elements.iname.value is the better style. Commented Dec 12, 2016 at 0:42
  • 1
    Have a look here and there Commented Dec 12, 2016 at 0:49

1 Answer 1

5

UPDATE

According to WHATWG 6.2.4 Named access on the Window object

The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following,...for all applet, embed, form, frameset, img, and object elements...


According to W3C DOM 2 HTML Specification 2.7.2.1 HTMLAllCollection

The following elements name attribute can be referenced as a property of the document object: anchor, applet, button, form, frame, iframe, img, input, map, meta, object, param, select, and textarea


This referencing approach is standard, but it's use is generally discouraged. A few reasons to avoid directly referencing DOM property or window object by name attributes are: variable shadowing, inadvertently scoping to the window object, major browser inconsistencies, etc. For details on why it should be avoided, read this section and this post.

This Snippet shows a stable and standard way of using form names as a reference document.forms and the referencing form names previously mentioned as well.

SNIPPET

var val1 = document.forms.fname.elements.iname.value;

console.log(val1);

var val2 = fname.iname.value;

console.log(val2);
<form name='fname'>
   <input name='iname' value="42">
</form>

Sign up to request clarification or add additional context in comments.

10 Comments

They're not asking about the document forms collection but rather about accessing forms by name directly on the document object.
This Snippet shows the better way of using form names as a reference and the referencing previously mentioned.
Are you sure this is non-standard?
@squint - You are quite correct. It's perfectly standard. It's described under section 3.1.3 DOM tree accessors of the HTML5 spec. Scroll down to the part that starts "The Document interface supports named properties. "
@squint Found the specs as well, updated accordingly. It's standard albeit a mess.
|

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.