<script>
$(document).ready(function() {
var table = $('table').DataTable({
searching: true,
paging: true,
ordering: true
});
//popup filter
$('th').each(function(index) {
var columnIndex = index;
var columnData = table.column(columnIndex).data().unique().toArray();
var filter = $('<div class="popup-filter"></div>');
filter.append('<input type="text" placeholder="Search">');
filter.append('<button class="sort">Sort</button>');
filter.append('<br>');
columnData.forEach(function(option) {
var textContent = $(document.createElement('div')).html(option).text();
filter.append('<label><input type="checkbox" class="filter-checkbox" data-filter-value="' + textContent + '">' + textContent + '</label><br>');
});
$(this).append(filter);
});
//close popup
$('th').click(function(event) {
$('.popup-filter').hide();
$(this).find('.popup-filter').toggle();
event.stopPropagation(); // prevent the click event from bubbling up
});
//close popup when clicking outside of it
$(document.body).on('click', function(event) {
if (!$(event.target).closest('.popup-filter').length) {
$('.popup-filter').hide();
}
});
//close popup when clicking enter in search
$('.popup-filter input[type="text"]').on('keyup', function(event) {
if (event.keyCode === 13) {
table.column($(this).closest('th').index()).search(this.value).draw();
$('.popup-filter').hide();
}
});
// search
$('.popup-filter input[type="text"]').on('keyup', function() {
table.column($(this).closest('th').index()).search(this.value).draw();
});
// sorting
$('.popup-filter').on('click', '.sort', function() {
var columnIndex = $(this).closest('th').index();
var order = table.column(columnIndex).order()[0];
if (order === 'asc') {
table.column(columnIndex).order('desc').draw();
} else {
table.column(columnIndex).order('asc').draw();
}
});
//checkbox
$('.popup-filter').on('change', '.filter-checkbox', function() {
var columnIndex = $(this).closest('th').index();
if ($(this).prop('checked')) {
//var filterValue = $(this).val();
var filterValue = $(this).data('filter-value');
console.log(filterValue);
//var filterValue = table.column(columnIndex).data(this.value).val();
//alert(filterValue);
table.column(columnIndex).search(filterValue).draw();
} else {
table.column(columnIndex).search('').draw();
}
});
});
</script>
I suspect the issue might be with "var table = $('table').DataTable({" but I'm not sure how to proceed with creating a web template first with the script and then applying it to all tables.