What's the point of HTML forms `name` attribute? - html

What's the point of the name attribute on an HTML form? As far as I can tell, you can't read the form name on submission or do anything else with it. Does it serve a purpose?

In short, and probably oversimplifying a bit: It is used instead of id for browsers that don't understand document.getElementById.
These days it serves no real purpose. It is a legacy from the early days of the browser wars before the use of name to describe how to send control values when a form is submitted and id to identify an element within the page was settled.

From the specification:
The name attribute represents the form's name within the forms collection.

Once you assign a name to an element, you can refer to that element via document.name_of_element throughout your code. It doesn't work to tell when you've got multiple fields of the same name, but it does allow shortcuts like:
<form name="myform" ...>
document.myform.submit();
instead of
document.getElementsByName('myform')[0].submit();

Here's what MDN has to say about it:
name
The name of the form. In HTML 4, its use is deprecated (id should be used instead). It must be unique among the forms in a document and not just an empty string in HTML 5.
(from <form>, Attributes, name)
I find it slightly confusing that specifies that it must be unique, non-empty string in HTML 5 when it was deprecated in HTML 4. (I'd guess that requirement only applies if the name attribute is specified at all?). But I think it's safe to say that any purpose it once served has been superseded by the id attribute.

You can use the name attribute as an "extra information" attribute - similarly as with a hidden input - but this keeps the extra information tied into the form, which makes it just a little simpler to read/access.

name attribute is not completely redundant vis-à-vis id. As aforementioned, it useful with <forms>, but less known is that it can also be used with with any HTMLCollection, such as the children property of any DOM element.
HTMLCollection, in additional to be a array-like object, will have named properties commensurate with any named members (or the first occurrence in case of non-unique name). It is useful to retrieve specific named nodes.
For example, in the following example HTML:
<div id='person1'>
<span name='firstname'>John</span>
<span name='lastname'>Doe</span>
<span name='middlename'></span>
</div>
<div id='person2'>
<span name='firstname'>Jane</span>
<span name='lastname'>Doe</span>
<span name='middlename'></span>
</div>
by naming each child, one can quickly and efficiently retrieve a named element, such as lastname, as such:
document.getElementById('person1').children.namedItem('lastname')
...and if there is no risk of 'length' being the name of a member element, (being that length is a reserved property of HTMLCollection), a more terse notation may be used instead:
document.getElementById('person1').children.lastname
DOM Living Standard 2019 March 29
An HTMLCollection object is a collection of elements...
The namedItem(key) method, when invoked, must run these steps:
If key is the empty string, return null.
Return the first element in the collection for which at least one of the following is true:
it has an ID which is key;
it is in the HTML namespace and has a name attribute whose value is key;

Related

Can I have multiple values in one HTML "data-" element?

Can I have multiple values in one HTML "data-" element? Similar to how a class can have multiple class names.
If possible, I would like to create a CSS/JS library that makes use of one "data-" element to house all of the library styles. For example:
<div data-library-name="xs-hidden col-md-10 col-xl-8 big-hero"></div>
That way, any of the programmers custom style rules can go into the elements class. My reasoning for this is to make readability easier, so together it would look like:
<div class="custom-style another-style" data-library-name="xs-hidden col-md-10 col-xl-8 big-hero"></div>
Can I have multiple values in one HTML "data-" element?
You can have a string. The spec doesn't define any particular format for the data in the attribute, which is designed to be processed by site specific JavaScript.
Similar to how a class can have multiple class names.
The class attribute takes a space separated list of classes.
Your JavaScript can your_data_attribute_value.split(" "); if you like.
Handling this with CSS would use the ~= attribute selector.
[att~=val]
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
AFAIK, I don't think data- attributes can convert that to an array. Instead, I think it'll interpret it as one value, but it is allowed.
If you want to do that, you'll probably have to split() it later in JavaScript into an array of usable values.
See this example on JSFiddle.net.
CSS has the shortcut .class selector but it actually is parsing the attribute named "class" as a list for space separated values. This is supported in the non-shortcut form by the following attribute selector:
[att~=val]
Represents an element with the att attribute whose value is a white space-separated list of words, one of which is exactly "val". If "val" contains white space, it will never represent anything (since the words are separated by spaces). If "val" is the empty string, it will never represent anything either.
Ref: http://www.w3.org/TR/CSS2/selector.html#class-html
As your question is tagged CSS you're perhaps looking for that. The rules how the parsing of attribute values is done is given in that document as well, so in case the javascript library you're trying to use on this (if any) won't cover that, it should be easy to add:
var list = $("div").data("library-name").split(/\s+/);
^^^^^^^^^^^^
This split with the white-space regular expression parses the string attribute value into an array with javascript and the Jquery library (for accessing the DOM and the data attribute).

Simple DOM/CSS Clarification? [WCAG F17 1.3.1]

http://www.w3.org/TR/WCAG-TECHS/F17.html
I have some issues understanding the criteria of this and what makes a website fail BASED on the series of tests involved.
Check for id and accesskey values which are not unique within the document.
Check that attribute values that have an idref value have a corresponding id value.
For tables that use the axis attribute, check that all values listed in the axis attribute have a corresponding id value in a table header cell in the same table.
For client-side image maps, check that the value of the usemap attribute has a corresponding id value if the usemap attribute is not a URI.
If step #1, step #3 or step #4 is true or step #2 is false, then this failure condition applies and the content fails the success criterion.
These are a series of requirements that make the HTML you have written valid.
1 is straightforward. There can't be more than one element on your page with the same ID. If you have multiple elements with the same ID on your page then when you call the Javascript function
document.getElementById("idnamehere")
then you will have trouble selecting all of them. If you want multiple items to have the same style, then you should be using the class attribute rather than ID. The ID must be unique!
2 If you have given an element the idref attribute, then it must correspond to an existing element with the id you have specified in the idref attribute. For example, if you wanted to use the following idref:
<p idref="data"></p>
Then there must be an existing id somewhere in your document, that looks something like:
<span id="data"></span>
You can't reference an id that doesn't exist!
3 I have never used the axis attribute before, but what I understand from reading that document and a small amount of Googling; if you want use the axis attribute then every cell must have a corresponding axis attribute supplied in the table header of the column it is in. Someone else may be able to expand on this.
4 Again, I have never used an ImageMap, but the W3C document has categorized this set of rules under the general theme of non-unique identities and mismatched references, so I can only assume that it is similar to 2 whereby, the imagemap has a corresponding usemap, which is referenced by its ID (unless, it has been specified as a URI).
I think the gist of this document is to enforce the concept that there should always be a corresponding attribute for the elements that require them, and your element ID's should always be kept unique.
If you are trying to fix something on your website, then http://validator.w3.org/ can be a very handy resource for pinpointing errors on your page and describing them. Hope this helps!

HTML input - name vs. id [duplicate]

This question already has answers here:
Difference between id and name attributes in HTML
(22 answers)
Closed 3 years ago.
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?
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 JavaScript with getElementsByName()
Shares the same namespace as the id attribute
Must begin with a letter
According to specifications 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 JavaScript 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> any more
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.
The name attribute is used for posting to e.g. a web server. The id is primarily used for CSS (and JavaScript). Suppose you have this setup:
<input id="message_id" name="message_name" type="text" />
In order to get the value with PHP when posting your form, it will use the name attribute, like this:
$_POST["message_name"];
The id is used for styling, as said before, for when you want to use specific CSS content.
#message_id
{
background-color: #cccccc;
}
Of course, you can use the same denomination for your id and name attribute. These two will not interfere with each other.
Also, name can be used for more items, like when you are using radio buttons. Name is then used to group your radio buttons, so you can only select one of those options.
<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />
And in this very specific case, I can further say how id is used, because you will probably want a label with your radio button. Label has a for attribute, which uses the id of your input to link this label to your input (when you click the label, the button is checked). An example can be found below
<input id="button_1" type="radio" name="option" /><label for="button_1">Text for button 1</label>
<input id="button_2" type="radio" name="option" /><label for="button_2">Text for button 2</label>
IDs must be unique
...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by
JavaScript scripts loaded in the page
CSS styles defined on the page
Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seems that it works.
Names are quite often unique but can be shared
...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's value gets posted back to server even though there are several related radio button controls with the same name.
Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.
When names can be duplicated
It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like ASP.NET MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.
Now suppose you have this scenario:
you have a view with a list of items of the same type
user usually works with one item at a time, so they will only enter data with one item alone and send it to server
So your view's model (since it displays a list) is of type IEnumerable<SomeType>, but your server side only accepts one single item of type SomeType.
How about name sharing then?
Each item is wrapped within its own FORM element and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.
This particular scenario can be seen on my Creative stories mini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.
name identifies form fields*; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
id identifies DOM elements; so they can be targeted by CSS or JavaScript.
* name's are also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.
name is the name that is used when the value is passed (in the URL or in the posted data). id is used to uniquely identify the element for CSS styling and JavaScript.
The id can be used as an anchor too. In the old days, <a name was used for that, but you should use the id for anchors too. name is only to post form data.
name is used for form submission in the DOM (Document Object Model).
ID is used for a unique name of HTML controls in the DOM, especially for JavaScript and CSS.
The name defines what the name of the attribute will be as soon as the form is submitted. So if you want to read this attribute later you will find it under the "name" in the POST or GET request.
Whereas the id is used to address a field or element in JavaScript or CSS.
The id is used to uniquely identify an element in JavaScript or CSS.
The name is used in form submission. When you submit a form only the fields with a name will be submitted.
The name attribute on an input is used by its parent HTML <form>s to include that element as a member of the HTTP form in a POST request or the query string in a GET request.
The id should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.
I hope you can find the following brief example helpful:
<!DOCTYPE html>
<html>
<head>
<script>
function checkGender(){
if(document.getElementById('male').checked) {
alert("Selected gender: "+document.getElementById('male').value)
}else if(document.getElementById('female').checked) {
alert("Selected gender: "+document.getElementById('female').value)
}
else{
alert("Please choose your gender")
}
}
</script>
</head>
<body>
<h1>Select your gender:</h1>
<form>
<input type="radio" id="male" name="gender" value="male">Male<br>
<input type="radio" id="female" name="gender" value="female">Female<br>
<button onclick="checkGender()">Check gender</button>
</form>
</body>
</html>
In the code, note that both 'name' attributes are the same to define optionality between 'male' or 'female', but the 'id's are not equals to differentiate them.
Adding some actual references to W3C documentation that authoritatively explain the role of the 'name' attribute on form elements. (For what it's worth, I arrived here while exploring exactly how Stripe.js works to implement safe interaction with the payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)
The following W3C documentation is relevant:
HTML 4: https://www.w3.org/TR/html401/interact/forms.html#control-name Section 17.2 Controls
HTML 5: https://www.w3.org/TR/html5/forms.html#form-submission-0 and
https://www.w3.org/TR/html5/forms.html#constructing-the-form-data-set Section 4.10.22.4 Constructing the form data set.
As explained therein, an input element will be submitted by the browser if and only if it has a valid 'name' attribute.
As others have noted, the 'id' attribute uniquely identifies DOM elements, but is not involved in normal form submission. (Though 'id' or other attributes can of course be used by JavaScript to obtain form values, which JavaScript could then use for Ajax submissions and so on.)
One oddity regarding previous answers/commenters concern about id's values and name's values being in the same namespace. So far as I can tell from the specifications, this applied to some deprecated uses of the name attribute (not on form elements). For example https://www.w3.org/TR/html5/obsolete.html:
"Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead."
Clearly, in this special case, there's some overlap between id and name values for 'a' tags. But this seems to be a peculiarity of processing for fragment ids, not due to general sharing of namespace of ids and names.
An interesting case of using the same name: input elements of type checkbox like this:
<input id="fruit-1" type="checkbox" value="apple" name="myfruit[]">
<input id="fruit-2" type="checkbox" value="orange" name="myfruit[]">
At least if the response is processed by PHP, if you check both boxes, your POST data will show:
$myfruit[0] == 'apple' && $myfruit[1] == 'orange'
I don't know if that sort of array construction would happen with other server-side languages, or if the value of the name attribute is only treated as a string of characters, and it's a fluke of PHP syntax that a 0-based array gets built based on the order of the data in the POST response, which is just:
myfruit[] apple
myfruit[] orange
Can't do that kind of trick with ids. A couple of answers in What are valid values for the id attribute in HTML? appear to quote the spec for HTML 4 (though they don't give a citation):
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
So the characters [ and ] are not valid in either ids or names in HTML4 (they would be okay in HTML5). But as with so many things html, just because it's not valid doesn't mean it won't work or isn't extremely useful.
If you are using JavaScript/CSS, you must use the 'id' of a control to apply any CSS/JavaScript stuff on it.
If you use name, CSS won't work for that control. As an example, if you use a JavaScript calendar attached to a textbox, you must use the id of the text control to assign it the JavaScript calendar.

Square brackets in HTML form arrays. Just conventional or with a meaning?

I frequently see, in particular in the PHP world, the following writing if you want to create a FORM array.
<input name="MyArray[]" />
<input name="MyArray[]" />
with the square brackets []. Nevertheless, the submit operation just passes the same key entry twice. It appears that the [] is just conventional that maps nicely to the PHP world array, but you would obtain the same result with just the following
<input name="MyArray" />
<input name="MyArray" />
Indeed, in django I get a list of two entries, regardless of the style used.
Is this true ? Are the [] just conventional, or there's actually a real meaning into it from the HTML and HTTP key/value info ?
They address a limitation of PHP, which doesn't generate an array automatically if multiple values with the same name are submitted, for example from a set of checkboxes or a multiple select. (IIRC it only returns the last value.)
Personally I've always thought it to be a pretty shoddy workaround. Even Classic ASP could cope with that without requiring client-side additions to markup. The server-side platform has no business imposing markup requirements on the client in this way.
It's just conventional.
The W3C states:
Let the form data set be a list of name-value-type tuples
and for each input element, on submit:
Append an entry to the form data set with name as the name, the value of the field element as the value, and type as the type.
The W3C does not mention the use of [] or uniqueness of the name attribute.

Can an HTML element have multiple ids?

I understand that an id must be unique within an HTML/XHTML page.
For a given element, can I assign multiple ids to it?
<div id="nested_element_123 task_123"></div>
I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.
No. From the XHTML 1.0 Spec
In XML, fragment identifiers are of
type ID, and there can only be a
single attribute of type ID per
element. Therefore, in XHTML 1.0 the
id attribute is defined to be of type
ID. In order to ensure that XHTML 1.0
documents are well-structured XML
documents, XHTML 1.0 documents MUST
use the id attribute when defining
fragment identifiers on the elements
listed above. See the HTML
Compatibility Guidelines for
information on ensuring such anchors
are backward compatible when serving
XHTML documents as media type
text/html.
Contrary to what everyone else said, the correct answer is YES
The Selectors spec is very clear about this:
If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector.Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.
Edit
Just to clarify: Yes, an XHTML element can have multiple ids, e.g.
<p id="foo" xml:id="bar">
but assigning multiple ids to the same id attribute using a space-separated list is not possible.
No. While the definition from W3C for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
My understanding has always been:
IDs are single use and are only applied to one element...
Each is attributed as a unique identifier to (only) one single element.
Classes can be used more than once...
They can therefore be applied to more than one element, and similarly yet different, there can be more than one class (i.e., multiple classes) per element.
No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:
<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>
and then use navigation to get what you really want.
If you are just looking to apply styles, class names are better.
You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes; put multiple class values into one attribute.
<div id="foo" class="bar baz bax">
is perfectly legal.
No, you cannot have multiple ids for a single tag, but I have seen a tag with a name attribute and an id attribute which are treated the same by some applications.
No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?
On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,
http://meyerweb.com/eric/articles/webrev/199802a.html
I'd like to say technically yes, since really what gets rendered is technically always browser-dependent. Most browsers try to keep to the specifications as best they can and as far as I know there is nothing in the CSS specifications against it. I'm only going to vouch for the actual HTML, CSS, and JavaScript code that gets sent to the browser before any other interpreter steps in.
However, I also say no since every browser I typically test on doesn't actually let you.
If you need to see for yourself, save the following as a .html file and open it up in the major browsers. In all browsers I tested on, the JavaScript function will not match to an element. However, remove either "hunkojunk" from the id tag and all works fine.
Sample Code
<html>
<head>
</head>
<body>
<p id="hunkojunk1 hunkojunk2"></p>
<script type="text/javascript">
document.getElementById('hunkojunk2').innerHTML = "JUNK JUNK JUNK JUNK JUNK JUNK";
</script>
</body>
</html>
Nay.
From 3.2.3.1 The id attribute:
The value must not contain any space characters.
id="a b" <-- find the space character in that VaLuE.
That said, you can style multiple IDs. But if you're following the specification, the answer is no.
From 7.5.2 Element identifiers: the id and class attributes:
The id attribute assigns a unique identifier to an element (which may
be verified by an SGML parser).
and
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
So "id" must be unique and can't contain a space.
No.
Having said that, there's nothing to stop you doing it. But you'll get inconsistent behaviour with the various browsers. Don't do it. One ID per element.
If you want multiple assignations to an element use classes (separated by a space).
Any ID assigned to a div element is unique.
However, you can assign multiple IDs "under", and not "to" a div element.
In that case, you have to represent those IDs as <span></span> IDs.
Say, you want two links in the same HTML page to point to the same div element in the page.
The two different links
<p>Exponential Equations</p>
<p><Logarithmic Expressions</p>
Point to the same section of the page
<!-- Exponential / Logarithmic Equations Calculator -->
<div class="w3-container w3-card white w3-margin-bottom">
<span id="exponentialEquationsCalculator"></span>
<span id="logarithmicEquationsCalculator"></span>
</div>
The simple answer is no, as others have said before me. An element can't have more than one ID and an ID can't be used more than once in a page. Try it out and you'll see how well it doesn't work.
In response to tvanfosson's answer regarding the use of the same ID in two different elements. As far as I'm aware, an ID can only be used once in a page regardless of whether it's attached to a different tag.
By definition, an element needing an ID should be unique, but if you need two ID's then it's not really unique and needs a class instead.
That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.
Classes are specially made for this, and
here is the code from which you can understand it:
<html>
<head>
<style type="text/css">
.personal{
height:100px;
width: 100px;
}
.fam{
border: 2px solid #ccc;
}
.x{
background-color:#ccc;
}
</style>
</head>
<body>
<div class="personal fam x"></div>
</body>
</html>
ID's should be unique, so you should only use a particular ID once on a page. Classes may be used repeatedly.
Check HTML id Attribute (W3Schools) for more details.
I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(