How to allow user to enter elements in an HTML table

Tony the Pony picture Tony the Pony · Nov 15, 2010 · Viewed 10k times · Source

I want to allow a user to enter a list of persons in a web application, and then submit them as one batch. Each row looks roughly like this:

<TR>
    <TD> <INPUT name="person.fname"> </TD>
    <TD> <INPUT name="person.lname"> </TD>
    <TD> <INPUT name="person.birthdate"> </TD>
</TR>

The form starts out with a single row of blank inputs, and I want a fresh row added to the list whenever the user fills in any of the fields -- i.e. the list grows on demand. Likewise, I want a row to disappear whenever the user clears all fields in it.

What is the easiest, most robust and most maintainable way to implement this?

Finally, how do I submit this table of values back to the server? What is the preferred way to name each field so that the server can create a list of Person entities based on the entered values?

Answer

Chris picture Chris · Nov 15, 2010

If you are familiar with jQuery, you can use the .change handler to catch them changing the field. Test to see if it's the last row and if there is data in it. If they have taken everything out of the row, remove it. jQuery has some great ways to do this, but it's all dependent on how you want to write it. If so, append the new row using jQuery's .append function. If you're using Python and cgi_app and you use the same name attribute for each type of cell, you can use form.getlist('fname[]') and it will return an array of the names.