Effortless, template-based dynamic tables

When you develop web applications for a living, sooner or later you’ll need to allow the user to edit collections of data. For instance:


Field 1 Options

To create something like this, I’ve been using a very rough script that simply replicated a hidden template row when required for several years. Eventually, I couldn’t stand its uglyness anymore and I decided to polish it a bit 😉

I’ve based my new script on prototype, thus keeping it short and elegant.

Let’s see the full code required to create the table above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- Ideally, this should go in <head> -->
<script type="text/javascript" language="javascript" src="http://files.tellini.info/dynamicTable.js"></script>

<table id="example1" class="dynamicTable">
    <tr class="template">
        <td><input type="text" name="test[#{rowId}]" /></td>
        <td>
            <input id="test#{rowId}" type="checkbox" name="cbTest[#{rowId}]" />
            <label for="test#{rowId}">Some option...</label>
        </td>
        <td><input class="deleteRow" type="button" value="Del" /></td>
    </tr>
    <tr>
        <th>Field 1</th>
        <th>Options</th>
        <th></th>
    </tr>
</table>
<input class="example1 addRow" type="button" value="Add" />

Simple, isn’t it?

Here’s what you need to know:

  1. the script automatically sets up all the tables with a dynamicTable class
  2. the template row is automatically hidden
  3. the ID of the table can be repeated as a class together with the addRow class to link the button to the table. If the button is already inside the table, you might just use the addRow class.
  4. the deleteRow class marks the button used to remove its containing row
  5. #{rowId} in the template will be replaced with an unique ID for every row that gets added. You’ll have to use sequential IDs starting from 0 for rows you add before serving the page to the client.

Exploiting prototype Classes, you can subclass DynamicTable and override addRow() or deleteRow() to perform whatever action you need on freshly created rows or when the user removes one.

By the way, you can find the code here.

Leave a Reply

Your email address will not be published. Required fields are marked *