HTML input - name vs. id

Simplicity picture Simplicity · Sep 19, 2011 · Viewed 362.7k times · Source

When using the HTML <input> tag, what is the difference between the use of the name and id attributes especially that I found that they are sometimes named the same?

Answer

Kumar Akarsh picture Kumar Akarsh · Sep 19, 2011

In HTML4.01:

Name Attribute

  • Valid only on <a>, <form>, <iframe>, <img>, <map>, <input>, <select>, <textarea>
  • Name does not have to be unique, and can be used to group elements together such as radio buttons & checkboxes
  • Can not be referenced in URL, although as JavaScript and PHP can see the URL there are workarounds
  • Is referenced in JS with getElementsByName()
  • Shares the same namespace as the id attribute
  • Must begin with a letter
  • According to specs is case sensitive, but most modern browsers don't seem to follow this
  • Used on form elements to submit information. Only input tags with a name attribute are submitted to the server

Id Attribute

  • Valid on any element except <base>, <html>, <head>, <meta>, <param>, <script>, <style>, <title>
  • Each Id should be unique in the page as rendered in the browser, which may or may not be all in the same file
  • Can be used as anchor reference in URL
  • Is referenced in CSS or URL with # sign
  • Is referenced in JS with getElementById(), and jQuery by $(#<id>)
  • Shares same name space as name attribute
  • Must contain at least one character
  • Must begin with a letter
  • Must not contain anything other than letters, numbers, underscores (_), dashes (-), colons (:), or periods (.)
  • Is case insensitive

In (X)HTML5, everything is the same except:

Name Attribute

  • Not valid on <form> anymore
  • XHTML says it must be all lowercase, but most browsers don't follow that

Id Attribute

  • Valid on any element
  • XHTML says it must be all lowercase, but most browsers don't follow that

This question was written when HTML4.01 was the norm, and many browsers and features were different from today.