Difference between id and name attributes in HTML
What is the difference between the id
and name
attributes? They both seem to serve the same purpose of providing an identifier.
I would like to know (specifically with regards to HTML forms) whether or not using both is necessary or encouraged for any reasons.
The name
attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id
attributes, but the same name
. When submitted, there is just the one value in the response - the radio button you selected.
Of course, there's more to it than that, but it will definitely get you thinking in the right direction.
Use name
attributes for form controls (such as <input>
and <select>
), as that's the identifier used in the POST
or GET
call that happens on form submission.
Use id
attributes whenever you need to address a particular HTML element with CSS, JavaScript or a fragment identifier. It's possible to look up elements by name, too, but it's simpler and more reliable to look them up by ID.
Here is a brief summary:
-
id
is used to identify the HTML element through the Document Object Model (via JavaScript or styled with CSS).id
is expected to be unique within the page. -
name
corresponds to the form element and identifies what is posted back to the server.
The way I think about it and use it is simple:
id is used for CSS and JavaScript/jQuery (it has to be unique on a page).
name is used for form handling on the server when a form is submitted via HTML (it has to be unique in a form - to some extent, see Paul's comment below).
See id= vs name=:
What’s the difference? The short answer is, use both and don’t worry about it. But if you want to understand this goofiness, here’s the skinny:
id= is for use as a target like this:
<some-element id="XXX"></some-element>
for links like this:<a href="#XXX"
.
name= is also used to label the fields in the message send to a server with an HTTP (HyperText Transfer Protocol) GET or POST when you hit submit in a form.
id= labels the fields for use by JavaScript and Java DOM (Document Object Model). The names in name= must be unique within a form. The names in id= must be unique within the entire document.
Sometimes the name= and id= names will differ, because the server is expecting the same name from various forms in the same document or various radio buttons in the same form as in the example above. The id= must be unique; the name= must not be.
JavaScript needed unique names, but there were too many documents already out here without unique name= names, so the W3 people invented the id tag that was required to be unique. Unfortunately older browsers did not understand it. So you need both naming schemes in your forms.
Note: attribute "name" for some tags like <a>
is not supported in HTML5.