· df · 2 min read

CRUD form using Datatables with dynamic Add & Delete rows

cruddatatablesWeb developmentJSONajaxjquery

Hope you guys have suffered same issues as me with Web Development to create forms with Create/Read/Update/Delete functionality. I really use "Datatables" (www.datatables.net) for displaying data in tabular format.  Datatables has got many advantages and is easily compatible with bootstrap stylings.

  • IE8+ support, major browser support and uses jQuery as its core
  • Can natively map JSON data
  • Searching and Filtering functionality with pagination Support
  • MultiLanguage support, ClientSide Sorting, AJAX based inputs
  • Can filter required Columns at front-end
Datatables is free but it's editor (editable tables) are paid. Hence I thought of putting together a simple table to use for editing and publishing data for POST purposes.
In Summary, what we are doing here is
  • Creating HTML stub with table headers within a form. Also add "Add Row" and "Delete Row" buttons with onclick actions attached to it and a "Submit" button
  • In your javascript, "on document load" create a datatable with built in "input=text" form for rows. This can be done using fnAddData
        function addRow() {
          $('table#myTable').dataTable().fnAddData([
            'input type="text" class="first_name" id="first_name_' + count + '">',   // Note the class name
            'input type="text" class="last_name" id="last_name_' + count + '">'
          ]);
    
      count++;
    }
  • Similarly for "Delete Row" action, bind it to  
     $("table#myTable").dataTable().fnDeleteRow(count - 1);
  • Using "Add Row" and "Delete Row" you can add/remove any number of rows.
  • When you Click the Submit button, the dataTable is scanned and fetched as Key-Value object pair. This is pushed into a JSON object Array.
  •       $("#submitButton").click(function() {
            oTable = $('#myTable').dataTable();
            var numColumns = oTable.fnGetData(0).length;
            var rules = [];                                     
    
        $.each(oTable.fnGetData(), function(i, row) {
          var rec = {};
          for (var c = 0; c < numColumns; c++) {
           // Extracting Class name as KEY
            var key = ($(row[c]).attr('class'));  
           // Dynamic Rows as VALUE          
            var value = ($('#' + key + '_' + i).val());     
            rec[key] = value;
          }
          rules.push(rec);
    
        })
    
        alert(JSON.stringify(rules));
    
    
      });

Below is Sample of editable Datatables


Pure web-based create/read/update/delete (CRUD) table with AJAX post functionality