Is it ok for an HTML element to have the same [name] as its [id]?

不问归期 提交于 2019-11-28 09:36:26

You use IDs for JavaScript manipulation.

You use Names for form field submission.

The two are not related. So setting both to the same value is OK, but it is not required.

Not only is it okay, it's quite common.

IDs are used for Javascript (and to a lesser extent, for CSS).

Names are used for form fields to specify the name for the submitted value.

However older versions of IE have known bugs that mean you're almost forced to specify them both the same in many cases. (assuming you want to support those older versions of IE, of course!)

The one thing to bear in mind though is that that IDs must be unique. Therefore, if you have radio buttons which all have the same name, you can't use the same ID for them all. In most other cases though, it's perfectly fine to have them the same.

Yup! This is absolutely fine.

id is the client-side identifier (for when looking up an element in the DOM)

name is used during form submission to POST/GET the values.

Outside of an input element there should be no need to use name at all. But giving input elements an id allows them to be looked up in the DOM in a consistent fashion.

I do it all the time (mostly because some browsers in the past - IE comes to mind - only use the name parameter when sending the form data). Using id's makes form validation code much cleaner, IMO.

zzzzBov

I just discovered the HTML4 answer to my question:

The id and name attributes share the same name space. This means that they cannot both define an anchor with the same name in the same document. It is permissible to use both attributes to specify an element's unique identifier for the following elements: A, APPLET, FORM, FRAME, IFRAME, IMG, and MAP. When both attributes are used on a single element, their values must be identical.

Now, I assume that the rule being applied to applet and iframe should, by extension, work for object and embed tags. In any event, using an identical name & id has produced no unusual events to date.

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