Penny Liu
Penny Liu

Reputation: 17468

Append DOM elements to the Datatables wrapper

I want to add rows to Datatables tbody using jQuery append() Method.

Here's the entire JavaScript code:

$('#meterGroup').DataTable();
$("#meterListGroup").html("<table id='meterGroup' class='table table-striped table-bordered' cellspacing='0' width='100%'><tbody></tbody></table>");
$("#meterGroup").append("<thead><tr><th>Meter ID</th><th>Energy Consumption (kW)</th><th>Usage Ratio (%)</th></tr></thead>");

var meterId = 1;
var meterConsumption = 155;
var meterRatio = 20;

for (var i = 1; i <= 40; i++) {
  $("#meterListGroup > table > tbody").append("<tr><td>" + meterId + "</td><td>" + meterConsumption + "</td><td>" + meterRatio + "</td></tr>");
  meterId++;
  meterConsumption++;
  meterRatio++;
}

and simple HTML:

<div id="meterListGroup"></div>

However, the results of the Datatables is not what I expected. Some element plugins was missing (e.g Search box, Pagination control, and so on.)

enter image description here

Where is the mistake? Is there a JSFiddle available for help?

$('#meterGroup').DataTable();
$("#meterListGroup").html("<table id='meterGroup' class='table table-striped table-bordered' cellspacing='0' width='100%'><tbody></tbody></table>");
$("#meterGroup").append("<thead><tr><th>Meter ID</th><th>Energy Consumption (kW)</th><th>Usage Ratio (%)</th></tr></thead>");

var meterId = 1;
var meterConsumption = 155;
var meterRatio = 20;

for (var i = 1; i <= 40; i++) {
  $("#meterListGroup > table > tbody").append("<tr><td>" + meterId + "</td><td>" + meterConsumption + "</td><td>" + meterRatio + "</td></tr>");
  meterId++;
  meterConsumption++;
  meterRatio++;
}
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h3><i class="fa fa-tachometer" aria-hidden="true"></i> Meter List Information</h3>
<!-- Meter List Information -->
<div id="meterListGroup"></div>

Upvotes: 2

Views: 2271

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58900

You need to initialize the table after you constructed it with html() and append().

$("#meterListGroup").html("<table id='meterGroup' class='table table-striped table-bordered' cellspacing='0' width='100%'><tbody></tbody></table>");

// ... skipped ...

$('#meterGroup').DataTable();

See updated example for code and demonstration.

Upvotes: 1

Related Questions