Time and again I find myself in need of an extendable form where users can add rows to the form directly. I have found that the best and easiest solution for this is to use the exellent DataTables plugin for jQuery. I will show you a full example of a simple implementation of this in this blog post.
section
Starting from the beginning. We need to make sure that we have the proper libraries available.
DataTables add/delete rows example
We are adding jQuery just before DataTables as DataTables requires jQuery.
Control buttons
We’ll add some control buttons to the tag.
id="controlButtons">
Add the form table
Also in your tag, please go ahead and add the actual table.
Take extra care in looking through the table structure. We started with giving the Now, add the JavaScript below to the very end of your So, what the JavaScript does is fairly straight forward. It The initialization of DataTables is done within We are using two of DataTables methods to add and remove rows from the table. We use an
id
set to myTable
. This will be used as a reference to our table in the next step. Also, the table consists of a and
.
Write the JavaScript to bind it all together
tag. Take some time to read it through.
$(document).ready()
. We tell DataTables which table to look for (table#myTable
) and then we pass some configuration to remove functionality like pagination that is not wanted in a form context.fnAddData()
to add new rows to the table. It takes an array of fields/columns.