I am using a datatable and that needs to have individual column based search feature along with global search
I am using the 2D array.
It does place the search boxes but its not doing the right search not it does a good global search
I have tried with
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.0/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.11.0/js/dataTables.bootstrap5.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.0/css/dataTables.bootstrap5.min.css">
</head>
<body>
<div id="example">
<!-->dynamic initialisation where first row of array will be headers<-->
</div>
<script>
$(document).ready(function() {
// Setup - add a text input to each footer cell
var dataHere = [
["Name", "Role", "Place", "ID", "Date"],
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$3,120"
],
[
"Garrett Winters",
"Director",
"Edinburgh",
"8422",
"2011/07/25",
"$5,300"
]
]
$(document).ready(function() {
var html = ''
for (var j = 0; j < dataHere[0].length; j++) {
html = html + '<td><input type="' + dataHere[0][j] + '" placeholder="Search ' + dataHere[0][j] + '" /></td>'
}
$("#example thead tr").html(html);
// DataTable
var table = $('#example').DataTable({
"data": dataHere,
initComplete: function() {
$('#example thead th').each(function() {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
this.api().columns().every(function() {
var that = this;
$('input', this.footer()).on('keyup change clear', function() {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
}
});
});
});
</script>
</body>
</html>
I need to implement like this but the serach boxes needed to be at the top
2
Answers
This works.
I took your starting point and made some modifications. The end result:
The main changes I made:
Ensure the
dataHere
row data matches the heading data in terms of number of values and data types.Provide a starting HTML structure with empty
<thead>
and<tbody>
tags, for convenience (makes the JavaScript code a bit easier).In JavaScript, build 2 header rows. This is to ensure sorting events are completely separate from filtering events. Otherwise, you will sort every time you try to filter, if there is only one heading row in the DataTable.
Included
orderCellsTop: true
in the DataTable definition. Following on from point (3), this tells DataTables that only the first heading row in the table is for sorting.Removed unneeded code. Because you are building the HTML table up-front, you already have the filters you need – you don’t need to repeat that logic in the DataTable initialization code.