Does a name attribute have to be unique in a HTML document?
I remember reading in the spec once that both the id
attribute and the name
attribute share the same namespace and have to be unique. Henceforth I've always tried to fulfill this requirement in my applications, dreading even to give the same id
and name
to the same element.
But lately I've started working with ASP.NET MVC 3, and it (like PHP) can use the same name
attribute on several input controls to form a collection of values at server-side. I tried to look up the relevant section in the spec - but failed to find it. Perhaps I have misunderstood something then, or read the wrong documentation?
How is it then? I want to produce as valid HTML as possible (both 4.01 and 5 in different apps). Can I use this trick without fear? Or would I be violating something and should better stick to unique values?
The name
attribute is only valid on the <form>
and form elements (<input>
,<textarea>
and <select>
). It's used to specify the name
to associate with the name/value pair that is submitted on a form post.
For example:
<input type="checkbox" name="foo" value="1" />
if checked will submit foo=1
. In the DOM you can reference form elements from the form.elements
collection by specifying the name
as the index. If name
is not unique, the collection returns an array of elements rather than the element. Modern DOM's support looking up form elements by name as:
document.getElementsByName(nameValue)
note: it always returns an array even if only one element is found.
id
attribute is from the XML world, and is a unique id for any node, not just form elements. Unlike the name
attribute it is valid on any HTML node. Also like the name
attribute, it must follow the valid identifier rules. The identifier should start with an alpha, and only contain alpha ([a-zA-Z]
), numbers, hyphen, underscore and colons (note ASP.NET breaks this rule by starting reserved IDs with a underscore - thus they will always fail an HTML/XML lint - actually some proxies strip them). To find any HTML element by id
you use:
document.getElementById(idvalue)
this only returns one DOM node.
The name
attribute is not unique. For instance, it is used to group radio buttons. It represents the value of a particular form property. id
s must be unique.
ID should be unique but you can use multiple form elements with the same NAME. This is standard for how radio buttons work so you can force one seletion of a radio button group.