datatable buttons bootstrap 4
To add DataTable buttons in Bootstrap 4, you need to include the necessary CSS and JavaScript files. Here's how you can achieve this:
- First, make sure you have included the required dependencies. Add the following CDN links in the
<head>
section of your HTML file:
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.0.1/css/buttons.bootstrap4.min.css">
- Next, include the DataTables and Buttons JavaScript files. Place the following script tags at the bottom of your HTML file, just before the closing
</body>
tag:
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.bootstrap4.min.js"></script>
- Now, initialize the DataTable with the buttons. Add the following JavaScript code:
<script>
$(document).ready(function() {
$('#example').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf', 'csv', 'print'
]
});
});
</script>
In this code, we set the dom
option to include the buttons. We then specify the buttons we want to display using the buttons
array.
- Finally, create a table with an id of "example" in your HTML file:
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>25</td>
<td>New York</td>
</tr>
<!-- Add more rows here -->
</tbody>
</table>
Replace the example data with your own data or dynamically generate it using server-side scripts.
That's it! You should now have DataTable buttons integrated into your Bootstrap 4 project.