I would like to combine datatables with dynamically loaded jquery tabs and don't know how to do it.
Here is my code:
index.jsp:
$(document).ready(function() {
$( "#tabs" ).tabs({
beforeLoad: function( event, ui ) {
ui.jqXHR.fail(function() {
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. "+
"If this wouldn't be a demo." );
});
}
});
$('#example').DataTable();
});
<div id="tabs">
<ul>
<li><a href="ajax/tab.jsp?a=1">Tab 1</a></li>
<li><a href="ajax/tab.jsp?a=2">Tab 2</a></li>
<li><a href="ajax/tab.jsp?a=3">Tab 3</a></li>
<li><a href="ajax/tab.jsp?a=4">Tab 4</a></li>
</ul>
</div>
tab.jsp:
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
</tr>
</tbody>
</table>
When we click Tab it will load ajax/tab.jsp?a=1
in a dynamic div.
So this happens each time you click a Tab.
But your Datatable
code is written just once which will get executed before the jsp
file is loaded
So your datatable doest show up.
To resolve this
$('#example').DataTable();
each time a Tab is clickedYou can use tabsbeforeload event of Tabs.
Note:
I have added timeout just to delay things so that jsp is loaded. If yous jsp takes more time to load try increasing timeout value.
Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Tabs - Default functionality</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
$("#tabs").tabs({
beforeLoad: function (event, ui) {
// load first time
setTimeout(function () {
$('#example').DataTable();
}, 30);
ui.jqXHR.fail(function () {
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo.");
});
}
});
// before tabload
$("#tabs").on("tabsbeforeload", function (event, ui) {
console.log("dd");
$("#example").remove(); // to avoide duplicate id as Datatable will not load for other Tabs
setTimeout(function () {
$('#example').DataTable();
}, 30);
});
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li><a href="ajax/tab.jsp?a=1">Tab 1</a></li>
<li><a href="ajax/tab.jsp?a=2">Tab 2</a></li>
<li><a href="ajax/tab.jsp?a=3">Tab 3</a></li>
<li><a href="ajax/tab.jsp?a=4">Tab 4</a></li>
</ul>
</div>
</body>
</html>