InLine Editing Using DataTable

Introduction

 
DataTables is a powerful Javascript library for adding interaction features to HTML tables. This article demonstrates how to edit/ update the datatable rows. Not only datatable, but this can also be useful for any HTML tables. Datatable editor is the licensed one, so we are handling the edit/ updating functionality in jQuery.
 

Qhat is Datatable?

 
If you haven’t read the introductory post on datatable, I would recommend reading the article this
 
Step 1
 
HTML part for datable creation:
  1. <div>    
  2.     <table width="100%" id="dtExample" class="display " cellspacing="0">    
  3.         <thead>    
  4.             <tr>    
  5.     
  6.                 <th>S.No</th>    
  7.                 <th style="display:none;">Id</th>    
  8.                 <th>Name</th>    
  9.                 <th>Age</th>    
  10.                 <th>City</th>    
  11.                 <th>State</th>     
  12.             </tr>    
  13.         </thead>    
  14.     </table>    
  15. </div>    
Step 2
 
Create datatable instance:
  1. $(document).ready(function () {    
  2.        fnLoadDataTableInstance()    
  3.    })    
  4.    function fnLoadDataTableInstance() {    
  5.        var dataSource = [    
  6.            { id: '101', name: 'Gowtham', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },    
  7.            { id: '102', name: 'Sudhan', age: 38, city: 'Ooty', state: 'Tamil Nadu' },    
  8.            { id: '103', name: 'Vignesh', age: 34, city: 'Erode', state: 'Tamil Nadu' },    
  9.            { id: '104', name: 'CSK', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },    
  10.            { id: '105', name: 'Arvind', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },    
  11.            { id: '106', name: 'Rahul', age: 38, city: 'Ooty', state: 'Tamil Nadu' },    
  12.            { id: '107', name: 'Raji', age: 34, city: 'Erode', state: 'Tamil Nadu' },    
  13.            { id: '108', name: 'Ananthi', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },     
  14.        ]     
  15.            
  16.        $('#dtExample').DataTable({    
  17.            dom: 'Bfrtip',    
  18.            data: dataSource,    
  19.            columns: [    
  20.                {    
  21.                    render: function (data, type, row, meta) {    
  22.                        return meta.row + meta.settings._iDisplayStart + 1;    
  23.                    }    
  24.                },    
  25.                { data: 'name'class'editable text' },    
  26.                { data: 'age' },    
  27.                { data: 'city' },    
  28.                { data: 'state' }    
  29.            ],    
  30.            "searching"false,    
  31.            "paging"true,    
  32.            "info"true,    
  33.            "language": {    
  34.                "emptyTable""No data available"    
  35.            },    
  36.            "fnRowCallback"function (nRow, aData, iDisplayIndex) {    
  37.                $("td:first", nRow).html(iDisplayIndex + 1);    
  38.                return nRow;    
  39.            },    
  40.        })    
  41.    }    
 
Step 3 
 
Create Edit and Delete buttons.
 
For datatable, the visible columns (table headers) which we created in the HTML part should match the columns which we creating in datatable instance.
 
Now we have to add two columns/table headers for Edit and Delete buttons.
  1. <div>    
  2.     <table width="100%" id="dtExample" class="display " cellspacing="0">    
  3.         <thead>    
  4.             <tr>    
  5.     
  6.                 <th>S.No</th>    
  7.                 <th style="display:none;">Id</th>    
  8.                 <th>Name</th>    
  9.                 <th>Age</th>    
  10.                 <th>City</th>    
  11.                 <th>State</th>    
  12.                 <th></th>    
  13.                 <th></th>    
  14.             </tr>    
  15.         </thead>    
  16.     </table>    
  17. </div>    
 Add an empty th for Edit and Delete buttons.
 
Step 4
 
Now render Edit and Delete buttons for the datatable creation.
  1.     $('#dtExample').DataTable({    
  2.         dom: 'Bfrtip',    
  3.         data: dataSource,    
  4.         columns: [    
  5.             {    
  6.                 render: function (data, type, row, meta) {    
  7.                     return meta.row + meta.settings._iDisplayStart + 1;    
  8.                 }    
  9.             },    
  10.             { data: 'name'class'editable text' },    
  11.             { data: 'age' },    
  12.             { data: 'city' },    
  13.             { data: 'state' },    
  14.             {    
  15.                 //edit button creation    
  16.                 render: function (data, type, row) {    
  17.                     return createButton('edit', row.id);    
  18.                 }    
  19.             },    
  20.             {    
  21.                 //delete button creation    
  22.                 render: function (data, type, row) {    
  23.                     return createButton('delete', row.id);    
  24.                 }    
  25.             }    
  26.         ],    
  27.         "searching"false,    
  28.         "paging"true,    
  29.         "info"true,    
  30.         "language": {    
  31.             "emptyTable""No data available"    
  32.         },    
  33.         "fnRowCallback"function (nRow, aData, iDisplayIndex) {    
  34.             $("td:first", nRow).html(iDisplayIndex + 1);    
  35.             return nRow;    
  36.         },    
  37.     })    
  38. }    
  39.     
  40. function createButton(buttonType, rowID) {    
  41.     var buttonText = buttonType == "edit" ? "Edit" : "Delete";    
  42.     return '<button class="' + buttonType + '" type="button">' + buttonText+'</button>';    
  43. }    
 
Now handle click events for each button.
 
When the user clicks the edit button, then the specific row buttons will change to Update & Cancel.
 
When a user clicks Update or Cancel, it will either update or cancel the changes and come back to display Edit & Delete buttons. 
 
Here, I have taken the example for editing one column which turned to a textbox in edit mode. Like that we can handle for other HTML controls. 
 
Step 5
 
Handle the Edit button:  
  1. $('#dtExample').on('click''tbody td .edit'function (e) {    
  2.     fnResetControls();    
  3.     var dataTable = $('#dtExample').DataTable();    
  4.     var clickedRow = $($(this).closest('td')).closest('tr');    
  5.     $(clickedRow).find('td').each(function () {    
  6.         // do your cool stuff    
  7.         if ($(this).hasClass('editable')) {    
  8.             if ($(this).hasClass('text')) {    
  9.                 var html = fnCreateTextBox($(this).html(), 'name');    
  10.                 $(this).html($(html))    
  11.             }    
  12.         }    
  13.     });     
  14.     
  15.     
  16.     $('#dtExample tbody tr td .update').removeClass('update').addClass('edit').html('Edit');    
  17.     $('#dtExample tbody tr td .cancel').removeClass('cancel').addClass('delete').html('Delete');    
  18.     $(clickedRow).find('td .edit').removeClass('edit').addClass('update').html('Update');    
  19.     $(clickedRow).find('td .delete').removeClass('delete').addClass('cancel').html('Cancel');    
  20.     
  21. });    
  22.     
  23. function fnCreateTextBox(value, fieldprop) {    
  24.     return '<input data-field="' + fieldprop + '" type="text" value="' + value + '" ></input>';    
  25. }    
Similar to the fnCreateTextBox, we can create HTML controls like dropdownlist, checkbox, radio button, and handle them.
 
 Step 6
 
Handle Cancel button: 
  1. $('#dtExample').on('click''tbody td .cancel'function (e) {    
  2.         fnResetControls();    
  3.         $('#dtExample tbody tr td .update').removeClass('update').addClass('edit').html('Edit');    
  4.         $('#dtExample tbody tr td .cancel').removeClass('cancel').addClass('delete').html('Delete');    
  5.     });    
  6.     
  7.     
  8.     function fnResetControls() {    
  9.         var openedTextBox = $('#dtExample').find('input');    
  10.         $.each(openedTextBox, function (k, $cell) {    
  11.             $(openedTextBox[k]).closest('td').html($cell.value);    
  12.         })    
  13.     }    
Step 7
 
Handle Update button:
  1. $('#dtExample').on('click''tbody td .update'function (e) {    
  2.     
  3.        var openedTextBox = $('#dtExample').find('input');    
  4.        $.each(openedTextBox, function (k, $cell) {    
  5.            fnUpdateDataTableValue($cell, $cell.value);    
  6.            $(openedTextBox[k]).closest('td').html($cell.value);    
  7.        })    
  8.     
  9.        $('#dtExample tbody tr td .update').removeClass('update').addClass('edit').html('Edit');    
  10.        $('#dtExample tbody tr td .cancel').removeClass('cancel').addClass('delete').html('Delete');    
  11.    });    
  12.     
  13. function fnUpdateDataTableValue($inputCell, value) {    
  14.        var dataTable = $('#dtExample').DataTable();    
  15.        var rowIndex = dataTable.row($($inputCell).closest('tr')).index();    
  16.        var fieldName = $($inputCell).attr('data-field');    
  17.        dataTable.rows().data()[rowIndex][fieldName] = value;    
  18.    }    
 

Summary

 
In this article, we have seen how to do inline editing for a datatable/HTML table.