Editable Data Table
HTML
<script src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.css">
<table id="datatable" class="display">
<thead>
<tr>
<th>Root Cause</th>
<th>Description</th>
<th> </th>
</tr>
</thead>
<tfoot>
<tr>
<th>Root Cause</th>
<th>Description</th>
</tr>
</tfoot>
</table>
JavaScript
$(document).ready(function() {
var tableData = [
{
"id": 1,
"name": "RC_1",
"description": "This is the first root cause"
},
{
"id": 2,
"name": "RC_2",
"description": "This is the second root cause"
}
];
var dataTable = $('#datatable').DataTable({
"data": tableData,
"columns": [
{ "data": "name" },
{ "data": "description" },
{
"data": null,
"defaultContent": '<button>Remove</button>'
}
]
});
$('#datatable').on('click', 'tbody > tr', function() {
alert();
if( !$(this).hasClass('selected') ) {
$('#datatable > tbody > tr.selected').removeClass('selected')
$(this).addClass('selected');
}
});
$('#datatable').on('dblclick', 'tbody td', function() {
var text = dataTable.cell($(this)).data();
var inputElement = document.createElement('input');
inputElement.type = "text";
inputElement.value = text;
inputElement.className = "editable";
this.innerHTML = '';
this.appendChild(inputElement);
$(inputElement).focus();
});
$('#datatable').on('change', '.editable', function() {
var inputVal = this.value;
var cell = dataTable.cell($(this).parent('td'));
var row = dataTable.row($(this).parents('tr'));
var oldData = cell.data();
cell.data(inputVal);
console.log(JSON.stringify(row.data()));
// Make an ajax call to update table.
// If the ajax call fails, put the old data back
// and show a warning.
...