Highlighting Labels

When designing HTML forms it’s important to correlate a field’s label with it’s input, select or textarea element. With this is mind, I wrote some javascript the other night which enhances the UI of a form which uses correctly marked-up inputs and labels. The javascript simply highlights a checkbox or radio’s corresponding label, giving each label a nice visual clue to the selected options. A demo can be viewed here.

To begin with the HTML has to be correctly marked up. By this I mean that each label’s for attribute references the id attribute of the corresponding checkbox. For example :

<input type="checkbox" id="myCheckbox" value="1" /> <label for="myCheckbox">My Checkbox Label</label>

Radio buttons are a little different as a group of options is created by giving each input element the same name attribute, so the markup here is :

<input type="radio" name="Fancy a pint?" id="radio1" value="yes" />
<label for="radio1">Yes</label>
<input type="radio" name="Fancy a pint?" id="radio2" value="no" />
<label for="radio2">No</label>

If you’re familiar with standards-compliant web design most of this stuff is second nature, but I thought I’d make it clear, otherwise the javascript won’t function correctly.

Include the javascript file using the script element (or add to an existing .js file, or paste into the head of your document). Then declare some CSS properties for a class called checked. This is the name of the class which the javascript dynamically assigns to the label element.

The javascript consists of 6 functions :

I’ve checked it on Firefox, Safari and IE6, but please let me know if there any problems with it.

Posted 3 years, 5 months ago on 24th January 2006.


Comments

It’s a nice, unobstrusive effect, but crikey, there’s a lot of code that goes into achieving it!

Matt · www · 3 years, 5 months ago


Aye, I was conscious of that, I’ll see if I can cut it down. To be honest the toggleLabel function is the main one. The other functions are basically utility functions that you’d probably have already.

Phil · www · 3 years, 5 months ago


This is the best one I’ve seen thus far. If they weren’t hard coded, they relied on a weird sort of labels count.

See http://www.tohir.co.za/2005/08/more-javascript-for-usability.html

Tohir · www · 3 years, 3 months ago


Commenting on this post has been disabled.

Skip Navigation