Greg's Blog

helping me remember what I figure out

IDs and Name Attributes

| Comments

Yesterday I stumbled across this little discovery relating to xHTML attributes name and id that you use for example in form tags such as input, e.g.: <input type=”text” name=”r_name” id=”r_name” value=”” size=20 />

Now I’d always gotten into the habit of setting the name attribute to same value as the id one, because as I understood it the name attribute would eventually be phased out and was thus hoping to future proof my forms. But what about this scenario involving making forms accessible and using radio buttons for selections?

<input type=”radio” name=”clientType” id=”clientType” value=”1” title=”radio button: for new client id” checked=”true” /><label for=”clientType”>By new</label><br /> <input type=”radio” name=”clientType” id=”clientType” title=”radio button: for old client id” value=”0” /><label for=”clientType”>By old</label>

Using my previously adopted technique the <label> tag could not fathom which field I was referring to. Why? Because IDs *must* be unique!! This is part of the W3C spec and I have known about this, but somehow never put 2 and 2 together when it came to forms. So here now is the new and improved radio button solution.

<input type=”radio” name=”clientType” id=”clientType_1” value=”1” title=”radio button: for new client id” checked=”true” /><label for=”clientType_1”>By new</label><br /> <input type=”radio” name=”clientType” id=”clientType_2” title=”radio button: for old client id” value=”0” /><label for=”clientType_2”>By old</label>

Downside is that these radio buttons are now no longer grouped by ID, instead they use the name attribute.