Should a name attribute be unique in an HTML document?

I remember how in the specifier I immediately read that both the id attribute and the name attribute use the same namespace and must be unique. From now on, I always tried to fulfill this requirement in my applications, fearing even to give the same id and name to the same element.

But lately, I started working with ASP.NET MVC 3, and it (for example, PHP) can use the same name attribute on several input elements to form a collection of values ​​on the server side. I tried to find the corresponding section in the specification, but could not find it. Perhaps I misunderstood something or read the wrong documentation?

How does this happen? I want the most efficient HTML possible (both 4.01 and 5 in different applications). Can I use this trick without fear? Or will I break something and stick to unique values ​​better?

+49
html unique
- Apr 01 2018-11-21T00:
source share
3 answers

The name attribute is valid only for <form> and form elements ( <input> , <textarea> and <select> ). He used to indicate name to associate with a name / value pair that is sent to the form message.

For example:

 <input type="checkbox" name="foo" value="1" /> 

if the flag is sent foo=1 . In the DOM, you can reference form elements from the form.elements collection by specifying name as an index. If name not unique, the collection returns an array of elements, not an element. Modern DOM support for finding form elements by name:

  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 identifier for any node, not just form elements. Unlike the name attribute, it is valid for any HTML node. Like the name attribute, it must follow the rules of a valid identifier. Certain ones must start with alpha and contain only alpha ( [a-zA-Z] ), numbers, hyphens, underscores, and colons (note: ASP.NET violates this rule by running reserved identifiers with underscores - this way they will always exit building HTML / XML lint - in fact, some proxies share them). To find any HTML element using id , you use:

 document.getElementById(idvalue) 

this returns only one DOM node.

+42
Apr 01 '11 at 20:32
source share

The name attribute is not unique. For example, it is used to group switches. It represents the value of the property of a particular form. id must be unique.

+15
Apr 01 '11 at 20:32
source share

The identifier must be unique, but you can use several form elements with the same name. This is standard on how switches work so that you can force a group of switches.

+6
Apr 01 2018-11-11T00:
source share



All Articles