Monday, October 1, 2012

Automatic Unobtrusive Binding of Labels to Form Elements

One commonly forgotten feaure in HTML is that when creating web forms the labels related to input elements should be related to them.  In the simplest terms it is done like so:

<label for="myItem">My Label</label><input id="myItem">
The benifit to doing this is that browser will automatically focus the input element when the label is selected.  A little thing I know but it's not use in most sites doe to inconvenience.

Thus I have the following bit of javascript to automatically do the same thing.  It looks for any unbound  labels and binds them to the next input, text area, or select item down the DOM tree from them.  That is the next matching element within the same parent that the label is in.  This method will also work if the input fields don't have ID's associated with them as an added bonus.

 To use just include this in a global script running on your site and it will do the work with no noticeable overhead.  This does require jQuery to work.
$(document).ready(function () {
  $("form label").each(function() {
    if (typeof $(this).attr("for") == "undefined" || $("#" + $(this).attr("for")).length == 0) {
      nextControl = $(this).next("input,textarea,select");
      if (nextControl.length > 0) {
        if (typeof nextControl.attr("id") != "undefined") {
          $(this).attr("for", nextControl.attr("id"));
        } else {
          $(this).click(function() {

No comments: