Reputation: 3353
I'm using Bootstrap 3's modal classes and Datatables 1.10 to create a confirmation modal dialog that contains a dynamic datatable. Each time the modal is displayed I need to replace the rows in the table, thus I'm using the datatables API to clear and add rows dynamically. The problem I'm having is that datatables is creating another table and adding the rows to it, rather than adding the rows to the existing table that contains the headers. Below is some of the markup, javascript and a link to a JSFiddle that illustrates this behavior.
What am I doing wrong here? Is this a datatables bug?
JSFiddle illustrating this behavior
html
<body>
<div id="theModal" class="modal fade" hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<div>
<table id="foobar" class="table table-condensed table-striped table-bordered small">
<thead>
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
<th>col 4</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="container-fluid">
<div class="row">
<div class="col-xs-6">
<a href="#" id="theButton" role="button" class="btn btn-primary" >show modal</a>
</div>
</div>
</div>
</body>
javascript
var theTable;
$(document).ready(function(){
$('#theButton').click(function(e) {
// just illustrating my dynamic data....
var data = ['data 1', 'data 2', 'data 3', 'data 4']
showTheModalTable(data);
});
theTable = $('#foobar').dataTable({
"searching": false,
"ordering": false,
"paging" : false,
"scrollY": "300px",
"scrollCollapse": true,
"info" : true
});
});
function showTheModalTable(data){
theTable.api().clear();
theTable.api().row.add(data);
$('#theModal').modal();
theTable.api().draw();
}
Upvotes: 0
Views: 4740
Reputation: 4652
http://jsfiddle.net/2Lo1qzk2/12/
The dataTable has a problem when the table is hidden when creating. Use the modal event shown.bs.modal and at that moment define your dataTable and add rows
var theTable;
$(document).ready(function () {
$('#theButton').click(function (e) {
showTheModalTable();
});
theTable = $('#foobar').dataTable({
"searching": false,
"ordering": false,
"paging": false,
"scrollY": "300px",
"scrollCollapse": true,
"info": true
});
});
function showTheModalTable() {
$('#theModal').modal();
}
$('#theModal').on('shown.bs.modal', function (e) {
var data = ['data 1', 'data 2', 'data 3', 'data 4']
theTable.api().clear();
theTable.api().row.add(data).draw();
})
Upvotes: 2