Return to Snippet

Revision: 50434
at August 21, 2011 20:05 by alberomo


Initial Code
function focusLabels() {
  if (!document.getElementsByTagName) return false;
  var labels = document.getElementsByTagName("label");
  for (var i=0; i<labels.length; i++) {
    if (!labels[i].getAttribute("for")) continue;
    labels[i].onclick = function() {
      var id = this.getAttribute("for");
      if (!document.getElementById(id)) return false;
      var element = document.getElementById(id);
      element.focus();
    }
  }
}

Initial URL


Initial Description
A JS function that put the focus in the form field associated to a label element whenever is clicked. The for atributte of the label element must match the id attribute of the associated form field.
It takes no arguments.
From book Dom Scripting by Jeremy Keith

Initial Title
focusLebels Function

Initial Tags
javascript, DOM

Initial Language
JavaScript