Applying Datatables to a dynamically created table.
Applying Datatables to a dynamically created table.
jswaringen
Posts: 4Questions: 2Answers: 0
I'm creating a table in JavaScript that only occurs after a callback. So the table isn't in the DOM to begin with. How can I apply Datatables to get it to format the table properly.
My code that builds the table looks something like this:
$.getJSON(LMEmpAPI,
{
// Input fields (parameters)
lname: $('#LName').val(),
fname: $('#FName').val()
})
.done(function(data) {
var ADDiv = '';
if (data.length > 0) {
// Build Table Header
if (data.length > 49) {
ADDiv +=
'<p class=\"alert\">Search returned more than 50 records. Please supply more specific search parameters.</p>';
} else {
ADDiv =
'<table id="lookup" class="table dataTable no-footer" role="grid" style="width: 100%"><thead><tr><th> </th><th>LM People Id</th>' +
'<th>Last Name</th><th>First Name</th><th>Work Phone</th><th>Email Address</th><th>NT UserId</th></tr></thead><tbody>';
$.each(data,
function(i) {
ADDiv += '<tr><td><a href=\"#\" data-ntid=\"' +
data[i].NT_ID +
'\')">Select</a></td>';
ADDiv += '<td>' +
data[i].LMPID +
'</td><td> ' +
data[i].lastName +
'</td><td> ' +
data[i].firstName +
'</td><td>';
ADDiv += data[i].workPhone +
'</td><td>';
ADDiv += data[i].emailAddress +
'</td><td>';
ADDiv += data[i].NT_ID +
'</td></tr>';
});
ADDiv += '</tbody></table><br/><br/>';
}
} else {
ADDiv = '<h3>No Records Found in Active Directory.</h3><br>';
}
if (data.length > 50) {
ADDiv +=
'<h4>Search returned more than 50 records. Please supply more specific search parameters.</h4><br>';
}
$('#ADEmp').html(ADDiv.toString());
$('#ADEmp > ');
});
Any help is GREATLY appreciated.
This discussion has been closed.
Answers
at its simplest something like this would likely be enough:
you can go as complicated with it as you want but for just simply creating the columns and populating them, something like that should be enough run it
if you plan on dynamically deleting and adding tables without ever reloading the page it may get more complicated but the principle should remain similar
You could init Datatables after your code places the table in the DOM. Which in the simplest case you could just use the Zero Config example.
Another option is use Datatables to build the table using the returned JSON. This is an example:
https://datatables.net/examples/data_sources/js_array.html
Kevin