views:

53

answers:

2

I noticed that if you wrap a radio button or checkbox in a label, the whole thing becomes clickable, even without a for/id pair (in fact, it seems to ignore this because I screwed it up!)

Example:

<label><input type="checkbox"> some text</label>

Then "some text" becomes clickable to check the box. I tested it in FF, Chrome and Opera, and IE8, does anyone know if it works in older browsers, like IE6?

+1  A: 

Yes, that's the intended behaviour.

http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.9

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

It looks like this doesn't actually work in IE6 (haven't tried other versions). If you already have something like jQuery loading on your page, then you could come up with a workable solution fairly easily:

if ($.browser.msie) {
    $('label:has(:input):not([for])').each(function() {
        var $t = $(this)
            , $in = $t.find(':input')
        ;
        if (!$in.attr('id')) {
            // use this, or make a proper GUID...
            $in.attr('id', 'input_' + (Math.random() * 1000000));
        }
        $t.attr('for', $in.attr('id'));
    });
}
nickf
So it works across all browsers then? Sweet. Saves me some hassle.
Mark
@Mark: bugger! I just tested it in IE6 (using a XHTML doctype) and it doesn't work.
nickf
(it's not doctype dependent)
BalusC
Oh well... I guess if you can't be bothered to upgrade your browser, you have to go the extra mile and actually click in the box ;) I am using jquery though... so maybe I'll give that a whirl.
Mark
+1  A: 

Wrapping label elements are broken in Internet Explorer up until version 7. Link (Google Cache to bypass the registration annoyance).

toscho