Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created July 23, 2009 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sstephenson/153257 to your computer and use it in GitHub Desktop.
Save sstephenson/153257 to your computer and use it in GitHub Desktop.
// In most browsers, a <label> tag around a form field, e.g.:
//
// <label>
// <input type="checkbox" id="private" name="private">
// This message is private
// </label>
//
// works just as if you'd specified a for= attribute on the label
// for the first visible field inside the label. In Safari 4, this
// seems not to be the case (i.e. the for= attribute is required).
//
// The following code watches the page for all clicks on <label>s
// and automatically sets the for= attribute, if not present, to
// the first visible form field.
document.observe("mousedown", function(event) {
var label = event.findElement("label");
if (label && !label.hasAttribute("for")) {
var element = label.down("input[type=radio], input[type=checkbox], input[type=submit]," +
"input[type=text], input[type=password], select, textarea");
if (element) {
label.writeAttribute("for", element.identify());
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment