I just want to post an example of how to configure the DataTables jQuery plug-in. Let’s say that I have a tree and that every time a node in the tree is clicked a new request is sent to the server and the data in the DataTables plug-in should be updated.
The HTML will look like this
<html>
...
<script type="text/javascript" src="./js/datatables-1.8.1/js/jquery.dataTables.js"></script>
...
<div id="content-table">
<table id="class-table">
</table>
</div>
...
</html>
Now let's say that I have a JSON response from the server that looks like this:
body : {
obj [ {
col1 : "valCol1",
col2 : "valCol2"
} ]
}
Now I need a JavaScript function that is going to create/update the data in the table every time that the response is obtained from the server.
loadDataTable = function(data) {
var view = $('#class-table');
var modelList = data.body.obj;
if ($('#columnHeader').length) {
var data = [];
for ( var i = 0; i < modelList.length; i++) {
data[i] = [
'<input type="checkbox" name="row-selected" value="false" />',
modelList[i].valCol1, modelList[i].valCol2 ];
}
view.dataTable().fnClearTable();
view.dataTable().fnAddData(data);
} else {
var html = '';
html += '<thead id="columnHeader">';
html += '<tr>';
html += '<th id="column-check"></th>';
html += '<th name="col1">Column 1</th>';
html += '<th name="col2">Column 2</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for ( var i = 0, count = modelList.length; i < count; i++) {
html += '<tr>';
html += '<td><input type="checkbox" name="row-selected" value="false"></td>';
html += '<td>' + modelList[i].valCol1 + '</td>';
html += '<td>' + modelList[i].valCol2 + '</td>';
html += '</tr>';
}
html += '</tbody>';
view.append(html);
var oTable = view.dataTable({
"sScrollY" : "200px",
"bPaginate" : false,
"bDestroy" : true
});
/* Adjust the size of the Table */
$(window).bind('resize', function() {
oTable.fnAdjustColumnSizing();
});
}
};
References:
Advertisement