Does a name attribute have to be unique in a HTML document?

后端 未结 3 890
一生所求
一生所求 2020-11-28 11:53

I remember reading in the spec once that both the id attribute and the name attribute share the same namespace and have to be unique. Henceforth I\

相关标签:
3条回答
  • 2020-11-28 12:10

    The name attribute is not unique. For instance, it is used to group radio buttons. It represents the value of a particular form property. ids must be unique.

    0 讨论(0)
  • 2020-11-28 12:22

    The name attribute is only valid on the <form> and form elements (<input>,<textarea> and <select>). It's used to specify the name to associate with the name/value pair that is submitted on a form post.

    For example:

    <input type="checkbox" name="foo" value="1" />
    

    if checked will submit foo=1. In the DOM you can reference form elements from the form.elements collection by specifying the name as the index. If name is not unique, the collection returns an array of elements rather than the element. Modern DOM's support looking up form elements by name as:

     document.getElementsByName(nameValue)
    

    note: it always returns an array even if only one element is found.

    id attribute is from the XML world, and is a unique id for any node, not just form elements. Unlike the name attribute it is valid on any HTML node. Also like the name attribute, it must follow the valid identifier rules. The identifier should start with an alpha, and only contain alpha ([a-zA-Z]), numbers, hyphen, underscore and colons (note ASP.NET breaks this rule by starting reserved IDs with a underscore - thus they will always fail an HTML/XML lint - actually some proxies strip them). To find any HTML element by id you use:

    document.getElementById(idvalue)
    

    this only returns one DOM node.

    0 讨论(0)
  • 2020-11-28 12:22

    ID should be unique but you can use multiple form elements with the same NAME. This is standard for how radio buttons work so you can force one seletion of a radio button group.

    0 讨论(0)
提交回复
热议问题