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.
Use
name
attributes for form controls (such as<input>
and<select>
), as that's the identifier used in thePOST
orGET
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.name
is deprecated for link targets, and invalid in HTML5. It no longer works at least in latest Firefox (v13). Change<a name="hello">
to<a id="hello">
The target does not need to be an
<a>
tag, it can be<p id="hello"
> or<h2 id="hello">
etc. which is often cleaner code.As other posts say clearly,
name
is still used (needed) in forms. It is also still used in META tags.If you're not using the form's own submit method to send information to a server (and are instead doing it using javascript) you can use the name attribute to attach extra information to an input - rather like pairing it with a hidden input value, but looks neater because it's incorporated into the input.
This bit does still currently work in Firefox although I suppose in the future it might not get allowed through.
You can have multiple input fields with the same name value, as long as you aren't planning to submit the old fashioned way.
name Vs id
name
<button>, <form>, <fieldset>, <iframe>, <input>, <keygen>, <object>, <output>, <select>, <textarea>, <map>, <meta>, <param>
id
Id : 1) It is used to identify the HTML element through the Document Object Model (via Javascript or styled with CSS). 2) Id is expected to be unique within the page.
Name corresponds to the form element and identifies what is posted back to the server. Example :
Based on personal experiences and according to the W3 Schools description for attributes:
ID is a Global Attribute and applies to virtually all elements in HTML. It is used to uniquely identify elements on the Web page, and its value is mostly accessed from the frontend (typically through JavaScript or jQuery).
name is an attribute that is useful to specific elements (such as form elements, etc) in HTML. Its value is mostly sent to the backend for processing.
https://www.w3schools.com/tags/ref_attributes.asp