Despite its moniker, name
is an unusual and often misunderstood HTML attribute. Its use is valid in the context of just over a dozen elements, only half of which are relevant to modern web development:
<button>
, <fieldset>
, <form>
, <iframe>
, <input>
, <output>
, <select>
, <textarea>
As you can see, name
is most commonly associated with HTML form elements, and it is in that context that most developers will encounter the attribute on a day-to-day basis.
Why Use Name?
name
is frequently employed to associate a form element with a value for a backend process, such as a PHP form validation script. A simple example with radio buttons shows how the attribute is used:
<form>
<fieldset>
<legend>Gender</legend>
<label>Male<input type="radio" value="m"></label>
<label>Female<input type="radio" value="f"></label>
<input type="submit" value="Go">
</fieldset>
</form>
In this code, the radio buttons in the form could both be turned on at the same time, and reported equally as valid values to the backend script. For the sake of simplicity, let’s assume that we want a binary response to gender*: we can’t use id
to gather a single value, as an id
value must always be unique, so instead we’ll turn to name
:
<label>Male<input type="radio" value="m" name="gender"></label>
<label>Female<input type="radio" value="f" name="gender"></label>
Now not only do the radio buttons turn each other on and off, but the form now reports a single variable of gender to the backend script, with one of two possible values: m or f
Regulations & Variations
It’s usually easiest to match the name
and id
values in form elements, for easier management of data:
<input type="text" name="personname" id="personname">
The oddities of name
continue into its association with JavaScript. In general, id
is associated with front-end technologies (HTML, CSS and JavaScript) and name
with backend (PHP, Perl, etc). However, there’s a weird exception for JavaScript. We’re very used to accessing elements in the DOM via document.getElementById
and document.querySelector
, but these are relatively roundabout methods compared to what we can do with name
. For example, in the completed form above:
<form onsubmit="alert(gender.value)">
In certain contexts, we can directly reference name
in JavaScript: no need for a variable, and no long syntax to remember. (document.getElementsByName()
also works, except it returns an array).
This feature of name
becomes particularly useful when dealing with relatively complex forms that use a lot of scripting, such as online calculators.
* Read why binary gender forms should be never be used
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.