name
, id
, and class
have fundamentally different purposes.
name
is for form element names and is not required to be unique (in fact, sometimes you need to reuse the same name
).
id
is, as the name indicates, an identifier for an element and must be unique in the document as a whole.
class
is primarily for presentation (although it sometimes used for hooking up client-side UI as well) and contains a list of classes for the element, not just a single class. If you used class
for form field identification, which of the possibly-several classes would you use?
Ways you might use the same name
on more than one field:
You can use the same name
in different forms without there being any conflict.
You use the same name
within a form for radio buttons that should be grouped together.
You can use the same name
within a form for multiple other kinds of elements whose values should all be sent to the server.
In contrast, id
must be unique — not only within the form, but within the entire document.
#3 might need an example for clarity. Suppose you have:
<form action="example" method="get">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="submit" value="Send">
</form>
If the user fills in a
, b
, and c
in those three text fields and sends the form, this is the query string:
?foo=a&foo=b&foo=c
Notice that foo
was repeated. The receiving resource can access all three of those values. (Perhaps you're listing tags for a post, or all of your children's names, or...)