Today I’ve been working on a very long form which needs client-side validation (as well as server-side validation, of course) and tooltips for most of the fields. For users without JavaScript, the tooltips are all shown next to each field. When JavaScript is enabled, however, the tooltips are all hidden at onload and then appear when a field gains focus. When a field loses focus, its value is validated with JavaScript and if this fails, an error message is shown next to that field.

I started doing this the way I usually do events, by putting onfocus and onblur events in the HTML on each field. It worked, but there are so many fields and it became a pain to put this in every field. I find that lots of JavaScript often decreases the readability of HTML, too.

I thought, “there must be a way to use JavaScript itself to add these events to each field”. It turns out that there is:

fields = document.getElementsByTagName('input');
for (i=0; i<fields.length; i++) {
 fields[i].onfocus = function() { ... };
 fields[i].onblur = function() { ... };
}

Now the events code is unobtrusive in the HTML. Users without JavaScript don’t have to download the events code, the HTML is more readable and I need to do a lot less copying and pasting!