javascript name vs ID

戏子无情 提交于 2019-12-01 04:20:58

The ultimate guide in this is the HTML specification.

Things that stand out there:

  • id is valid for any HTML element, while name only applies to a select few (a, input, textarea and maybe a few others).
  • An input (and textarea) element requires the name to be set if you want it to be submitted.

The name attribute is used during submitting the form, i.e. to create a name-value pair that will be processed to the server. The id attribute is used to locate and element in the DOM. Usually the name is used only on the form elements

References:

http://www.w3.org/TR/html401/interact/forms.html
http://www.w3schools.com/html/html_forms.asp

I typically use both. As you mentioned, name is useful for using the data via JavaScript and also once it has been submitted. Feel free to use additional characters in the name as needed: I tend to use []s in my names when the input will be used in an array server-side.

The id attribute can be used for accessing the element via JS/the DOM. It is also used by <label>'s for attribute. If you do this with checkboxes, for example, clicking on the label will cause the box to become checked. That's a big plus for usability.

I consider it good practice to have a name and id for each form element. The reason being that if you want to add labels, or styling via sytlesheets (which you should be doing), then it makes sense to have both.

As for accessing it with javascript: the better way would be to go with the element's id, becuase if you change the name of the form everything breaks. This does not happen when you use the id.

I prefer using IDs, as the "function" (i.e.: what you're trying to achieve) of your code isn't tied up with in the semantics. For me, .GetElementById('myid') stands out more, and is more readable that just having "myid" scattered among the code. Plus you can more easily rename elements. That's my 2p worth!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!