Reputation: 469
I've spent several hours trying to figure out a way to do this. I have an array of objects containing data relative to the content of the table. My objects aren't related to the structure of the table (no 1 property per column). I need to store an object in each row so I can use it in the render
function.
I'm sorry I can't provide code samples, since everything I've tried didn't work. I can't get my head around the working of row().data()
and render
. Could anyone explain these to me with an example?
Let's say there is a cell in which I want to spawn a div. This div would depend on the data state
I'd have stored in the row. If it's at true
, the render function would generate a <div class="success>Ok</div>
, else it'd generate <div class="failure>No</div>
.
Upvotes: 2
Views: 3262
Reputation: 58880
Please see the code below for an example. Based on your description, I have added "Toggle" button that toggles state of a new data property state
that didn't exist in the initial dataset.
var data = [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800"
},
{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750"
}
];
$(document).ready( function () {
// Initial state
var g_stateInitial = true;
var table = $('#example').DataTable({
"data": data,
"columns": [
{ "data": "name"},
{ "data": "position" },
{ "data": "salary"},
{
"data": null,
"searchable":false,
"render": function(data, type, row, meta){
var state = (data.hasOwnProperty('state')) ? data.state : g_stateInitial;
if(type === "display"){
return (state) ? '<div class="success">OK</div>' : '<div class="failure">NO</div>';
} else {
return state;
}
}
},
{
"data": null,
"searchable":false,
"render": function(data, type, row, meta){
if(type === "display"){
return '<button type="button" class="btn-toggle">Toggle</button>'
}
return data;
}
}
]
});
$('#example tbody').on('click', '.btn-toggle', function(){
var $row = $('#example').DataTable().row($(this).parents('tr'));
var data = $row.data();
data.state = (data.hasOwnProperty('state')) ? !data.state : !g_stateInitial;
$row
.data(data)
.invalidate()
.draw(false);
});
});
.success {
color:#009900;
}
.failure {
color:#990000;
}
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.js"></script>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>State</th>
<th></th>
</tr>
</thead>
</table>
Upvotes: 2