[Javascript] accessing a <label>

Paul Novitski paul at juniperwebcraft.com
Mon Jun 4 10:03:12 CDT 2007


At 6/3/2007 06:47 PM, Rick Pasotto wrote:
> > > How do I access the <label> element associated with an <input>?
> > > I'd like to add a class to change the background if validation fails.
>
>The input *can* be inside the label thus giving an *implicit* reference
>but that doesn't work if the label and the input are, for example, in
>different cells of a table. An *explicit* reference using "for=" seems
>better to me and is what I was using.
>
><label for="name">Your Name:</label>
><input type="text" id="name" name="name" size="30"/>


My own preference is to use "for" to connect labels with input 
controls, even when the labels wrap the controls.

When using javascript to validate forms and display prompts adjacent 
to specific controls, I prefer to build an array of labels up front, 
each with its "for" id pointer in memory, for convenient scripting.

Keep in mind that there can be more than one label for a given control:

"More than one LABEL may be associated with the same control by 
creating multiple references via the for attribute."
http://www.w3.org/TR/html4/interact/forms.html#h-17.9

Example:

         <label for="distance">Enter the distance:</label>
         <input id="distance" ... />
         <label for"distance">km</label>

in which you can click on either "Enter the distance:" or "km" to 
bring focus to the input field.

In this way "for" is more like "class" than "id."  To be future-proof 
your script should anticipate an array of labels matching a given 
control id, not just one.

Warm regards,

Paul
__________________________

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com
+1-250-355-2541
skype juniperpaul 




More information about the Javascript mailing list