mozilla & the label element.
Posted: 2002-07-30 19:37:36
According to the HTML
4.01 specification, When a LABEL element receives focus, it
passes the focus on to its associated control.
On both Mac and
Windows, Internet Explorer 5.0 & later does just that.
Unfortunately, Mozilla & its derivatives don't quite get it right.
For those associated with input elements of
type="radio" or type="checkbox", clicking the
label element toggles the value of the checked
attribute, so I initially thought all was well. Then, in a post to the
css-discuss
mailing list, Tom Gilder pointed out that
for other types of input, focusing the label
doesn't work:
Because of this, the user can't enter text without explicitly focusing
the appropriate form control. I did some simple tests, and it turns out
that when a label receives focus, rather than correctly
passing focus, Mozilla fires the click() event for the
associated input:
Richard Livsey suggested adding
onclick="this.focus()" to the target input as
a workaround. This works as advertised, but is a bit of a hassle.
So, I wrote a script that takes advantage of Mozilla's DOM support to
work around the problem, using event
listeners to handle it on a per-document basis, rather than adding
onclick="this.focus()" to each input
individually:
function forceFocus(e){
formCtrl=e.target.getAttribute('for');
document.getElementById(formCtrl).focus();
}
if(document.addEventListener){
labels=document.getElementsByTagName("label");
for (var i=0;i<labels.length;i++){
obj=labels[i];
obj.addEventListener("click",forceFocus,false);
}
}
Place this script in your document's body,
after all form elements. If that's not an option, you can
place the following in the document's head, but you'll also
need to add onload="fixLabel()" to the document's
body element:
function forceFocus(e){
formCtrl=e.target.getAttribute('for');
document.getElementById(formCtrl).focus();
}
function fixLabel(){
if(document.addEventListener){
labels=document.getElementsByTagName("label");
for (var i=0;i<labels.length;i++){
obj=labels[i];
obj.addEventListener("click",forceFocus,false);
}
}
}
Update: 2002-07-31 20:21:17
It looks like Mozilla 1.1 is gonna address this issue, but it could be a while before it makes its way into AOL/Netscape's browsers.