focusLebels Function


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. function focusLabels() {
  2. if (!document.getElementsByTagName) return false;
  3. var labels = document.getElementsByTagName("label");
  4. for (var i=0; i<labels.length; i++) {
  5. if (!labels[i].getAttribute("for")) continue;
  6. labels[i].onclick = function() {
  7. var id = this.getAttribute("for");
  8. if (!document.getElementById(id)) return false;
  9. var element = document.getElementById(id);
  10. element.focus();
  11. }
  12. }
  13. }

Report this snippet


Comments


You need to login to view comments.