Majestic
Majestic

Reputation: 938

Datatables can't use sort by column or search in content

I'm creating a DataTable in a javascript function and when I do, the "search" filter does not appear and the column's sorting is not working. Actually, it looks like the CSS is not working anymore.

Here's my code :

<html>
<head>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/select/1.2.7/css/select.dataTables.min.css" rel="stylesheet"/>
</head>
<body>
	<div id="area-panel-content" class="col-md-12">
		<table id="example" class="display" style="width:100%">
			<thead>
				<tr>
					<th>Repository</th>
					<th>Date</th>
					<th>Action</th>
				</tr>
			</thead>
			<tbody>
				<tr><td>AAA</td><td>AAA</td><td>AAA</td></tr>
				<tr><td>BBB</td><td>BBB</td><td>BBB</td></tr>
			</tbody>
		</table>
	</div>
	<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
	<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
	<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>
	<script>
	$(document).ready(function() {
		var currentTable = $('#example').DataTable();
		fillDataTable();
	} );
	
	function fillDataTable() {
		var folders = "";
		for(var i = 0; i < 5; i++) {
			folders = folders+
			'<tr><td><i class="fa fa-folder" aria-hidden="true"></i>Event'+i+'</td><td>25/12/2018</td><td></td></tr>';
		}
		var tableStart = '<table id="example" class="display" style="width:100%"><thead><tr><th class="sorting" aria-sort="ascending">Repository</th><th class="sorting" aria-label="Column 2: activate to sort column ascending">Date</th><th>Action</th></tr></thead><tbody>';
        var tableEnd = '</tbody></table>';

        $("#area-panel-content").replaceWith('<div id="area-panel-content" class="col-md-12">'+tableStart+folders+tableEnd+'</div>');
	
	}
</script>
</body>
</html>

If you comment the function fillDataTable(), it's working fine. I need to create a DataTable like I'm trying to do it above snippet.

Could you help me out to understand what I'm doing wrong ? Many thanks.

Upvotes: 1

Views: 37

Answers (1)

ViqMontana
ViqMontana

Reputation: 5688

You are initialising your data table, then replacing it with another table. You need to initialise your datatable after you have created your dynamic table. Change your $(document).ready function to:

$(document).ready(function () {
  fillDataTable();
  $('#example').DataTable();
});

Ps. you are missing a reference to both jQuery and the jQuery DataTable library.

Upvotes: 1

Related Questions