Code

Semantic xHTML Forms

Working with Ruby on Rails for the past four years has been great. Switching over from the PHP world was pretty easy, yet I do do some coding in that area from time to time. One…

Working with Ruby on Rails for the past four years has been great. Switching over from the PHP world was pretty easy, yet I do do some coding in that area from time to time. One great thing about Rails is its simplicity when it comes to creating a quick scaffold dump. In simple terms, it takes a database table and outputs a form element for each column into HTML. This is a quick way to visually start inputing data, but if you look at the source code, it is not very useful for designers.

The typical output for a scaffold dump is as follows:

<form>
  <label for="email">Email</label>
  <input name="email" type="text" />
  ...
</form>

Pretty simple right? Now put on your CSS and designer hat. What do you think you could do with that output? Probably not a whole lot. That br tag is just horrendous.

This form is semi-accessible too, but we could make it even more accessible and also give more elements to work with for the CSS.

Enter the definition list

For all the forms I create and/or need to style I resort to using a definition list. By definition it fits perfectly with the use of forms. Typical forms come with two elements per column: a label and a corresponding entry field. The same thing comes with a definition list: a term (the label) and a definition (the entry field). Semantically this produces a double benefit — a more structured form for accessibility and just a few more elements to access through use of CSS.

<form>
  <dl>
    <dt>
      <label for="email">Email</label>
    </dt>
    <dd>
      <input name="email" type="text" />
    </dd>
    ...
  </dl>
</form>

Granted we are introducing more markup, but I believe that is perfectly fine. The form now is ready for better CSS styling and defaults well when CSS is turned off or used by screen readers.