Adding lines to table with jQuery and DataTables

July 27, 2013

Reading time ~2 minutes

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.


  </span>DataTables add/delete rows example<span class="nt">
  
  
  

We are adding jQuery just before DataTables as DataTables requires jQuery.

Control buttons

We’ll add some control buttons to the tag.

 id="controlButtons">
   onclick="addRow();">Add row
   onclick="deleteRow();">Delete row

Add the form table

Also in your tag, please go ahead and add the actual table.

 action="" method="POST">
   id="myTable">
    
      
        First name
        Last name
      
    
    
    
  
   type="submit">

Take extra care in looking through the table structure. We started with giving the

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

Now, add the JavaScript below to the very end of your tag. Take some time to read it through.

So, what the JavaScript does is fairly straight forward. It

The initialization of DataTables is done within $(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.

We are using two of DataTables methods to add and remove rows from the table. We use fnAddData() to add new rows to the table. It takes an array of fields/columns.