datatables: update table cell after button click
by Akram kamal
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<h1>update 'following' upon clicking 'follow' button</h1>
<table id="tblFollow">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>following</th>
<th>follow!</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>0</td>
<td><a data-following="false" class="follow" href="#"> </a></td>
</tr>
<tr>
<td>2</td>
<td>Bill</td>
<td>0</td>
<td><a data-following="false" class="follow" href="#"> </a></td>
</tr>
<tr>
<td>3</td>
<td>Anna</td>
<td>0</td>
<td><a data-following="false" class="follow" href="#"> </a></td>
</tr>
<tr>
<td>4</td>
<td>Dick</td>
<td>1</td>
<td><a data-following="true" class="follow" href="#"> </a></td>
</tr>
<tr>
<td>5</td>
<td>Jane</td>
<td>0</td>
<td><a data-following="false" class="follow" href="#"> </a></td>
</tr>
</tbody>
</table>
CSS
h1 {
font-size: 25px;
font-weight: bold;
margin: 0px 0px 25px 0px;
font-family: arial, helvetica;
}
table {
font-family: arial, helvetica;
width: 100%;
}
th {
font-weight: bold;
text-transform: uppercase;
}
td, th {
padding-top:5px;
padding-bottom:5px;
text-align: center;
}
a.follow {
width: 20px;
height:20px;
display: inline-block;
background: blue;
color: blue;
}
a.follow.active {
background: yellow;
color: yellow;
}
JavaScript
var table = $('#tblFollow');
table.dataTable({
sDom: "t",
aoColumns: [
null,
null,
null,
{ bSortable: false }
]
});
$("a.follow[data-following='true']").addClass('active');
table.on('click', 'a.follow', function(e){
$(this).toggleClass('active');
// update column following here...
var followingCell = $(this).parents('td').prev();
var txt = followingCell.text() == "1" ? "0" : "1";
followingCell.text(txt);
var rowIndex = table.fnGetPosition( $(this).closest('tr')[0] );
var aData = table.fnGetData( rowIndex );
aData[2] = txt;
return false;
});