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 .
上一篇: 我如何设置HTML <select>元素的默认值?
下一篇: HTML中的id和name属性之间的区别