Ian Bicking: the old part of his blog

Accidental WHAT-WG Implementing

Yesterday was kind of fun; I spent the whole day programming, with a clear direction and lots of forward movement. It's always very satisfying when that happens.

Of course, I was really just distracting myself, tweaking out a form that didn't need to be tweaked out. I was doing it primarily in Javascript, and was using the MochiKit library some; though unfortunately that library didn't help me a great deal, and I had to avoid spending the day simply creating enhancements to it because that really would be a total distraction. I'd probably have gotten by fine with a couple bits of DOM traversal code.

What I ended up spending my time on was a little Javascript validation and repeating fields library. About half-way through I realized I was implementing bits of the WHAT-WG Web Form spec (though with different names). Which is a good sign all around, I suppose. For instance, for repeating fields I could write:

<tr class="form-template" form-group="urlmap">
 <td class="field">URLMap:</td>
 <td><input type="text" template-name="urlmap-${number}.path"
      style="width: 30%" title="path">:
     <input type="text" template-name="urlmap-${number}.url"
      style="width: 60%" title="URL" value="http://">
     <button form-delete="1">-</button>
 </td>
</tr>

<tr class="add-button" id="urlmap-before">
 <td colspan=2>
   <button form-add="urlmap" form-before="urlmap-before">
     Add URL Map
   </button></td>
</tr>

Basically I look for elements with a form-template class (Web Forms uses a template attribute), and collect them (they are also hidden by CSS). And I look for buttons with a form-add (Web Forms uses type="add") and add onclick handlers for them. Then when you hit the button it clones the template and substitutes ${number} with next next highest index (Web Forms uses [urlmap]). Oh, and detect the buttons with form-delete attributes and set their onclick handlers to delete their enclosing row (Web Forms uses type="remove").

It works pretty nicely, and the resulting fields can be unpacked into a nice nested structure by variabledecode.

In the past I've looked at Web Forms longingly, but haven't been able to find a reference Javascript implementation (despite a Javascript implementation being central to WHAT-WG's strategy). This code wasn't particularly hard to write -- lots of boring looping (Javascript looping SUCKS!) and a few little quirks (Gecko doesn't like you to make up your own tags). At some point I'll probably convert it to use Web Form's specs exactly.

Created 20 Jul '05