I am adding bootstrap button on the export buttons of datatables. It does not seem to render. I am adding btn btn-primary but all that does is add a blue border to the button. How can I ake it a bootstrap primary button?
I also want to add some padding to the button. Is there a way to do that?
My code:
<table id="example" class="table table-sm table-hover">
<thead>
<tr>
<th>Date</th>
<th>Version</th>
<th>Count</th>
<th>Average</th>
</tr>
</thead>
<tbody></tbody>
</table>
let table = $('#example').DataTable({
data: data,
columns: [{
data: 'date'
}, {
data: 'version'
}, {
data: 'count'
}, {
data: 'avg'
}],
dom: 'lBfrtip',
buttons: [{
extend: 'csv',
text: 'Export',
filename: 'Export File',
className: 'btn btn-primary'
}, ]
});
My output:
I want the button to look like:
and I also want to add some padding between the button and Show 10 entries.
How do I do this?
Please see if this works. To space the Export button, you can use Bootstrap's spacing classes
Included styles & scripts
<!-- Bootstrap CSS and JQUERY-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
$(document).ready(function() {
let table = $('#example').DataTable({
columns: [{
data: data,
data: 'date'
}, {
data: 'version'
}, {
data: 'count'
}, {
data: 'avg'
}],
dom: 'lBfrtip',
buttons: [{
text: 'Export',
filename: 'Export File',
className: 'ml-3 btn btn-primary',
action: function ( e, dt, node, config ) {
alert( 'Pressed!' );
}
}, ]
});
});
Related
I have a php/javascript application (Apache 2.4 / php8 on Windows). I am using jquery DataTables (datatables.net) and have coded:
dom: 'Brftip',
buttons: ['excel']
for several of the tables in my application.
This works great when I build the table dynamically in javascript as the result of a selection in another table. However when I code that in a table that is built in my document ready function The button does not display. Below is the relavent section of my $(document).ready() function:
$(document).ready(function () {
$('#jobs').DataTable({
dom: 'Bfrtip',
buttons: ['excel'],
select: {
sytle: 'single',
items: 'row'
},
ajax: {
url: "php/joblist.php",
type: "POST",
dataSrc: "",
data: function (d) {
var activeOnlyCheckbox = document.getElementById("activeOnly");
if (activeOnlyCheckbox.checked) {
return JSON.stringify({activeOnly: 'yes'});
} else {
return JSON.stringify({activeOnly: 'no'});
}
}
},
paging: false,
scrollY: '60vh',
scrollCollapse: true,
columns: [
{data: "JOB_ID"},
{data: "LAST_START"},
{data: "LAST_FINISH"},
{data: "LAST_STATUS"}
],
"columnDefs": [{
"targets": 3,
"data": "LAST_STATUS",
"render": function (data, type, row, meta) {
if (screen.width > 1500) {
return "<div class='text-wrap status-column'>" + data + "</div>";
} else {
return "<div class='text-wrap status-column'>" + data + "</div>";
}
}
}]
});
});
What am I missing?
Here, I created dummy response data and populated it to the table to see if it will print an excel file, and it works just fine.
var data = [
{"JOB_ID": "1",
"LAST_START": "Random Data",
"LAST_FINISH": "More Random Data",
"LAST_STATUS": "Last one"}
]
$(document).ready(function() {
var table = $('#myTable').DataTable({
data: data,
paging: false,
scrollY: '60vh',
scrollCollapse: true,
select: {
sytle: 'single',
items: 'row'
},
ajax: {
url: "php/joblist.php",
type: "POST",
dataSrc: "",
data: function (d) {
var activeOnlyCheckbox = document.getElementById("activeOnly");
if (activeOnlyCheckbox.checked) {
return JSON.stringify({activeOnly: 'yes'});
} else {
return JSON.stringify({activeOnly: 'no'});
}
}
},
columns: [
{data: "JOB_ID"},
{data: "LAST_START"},
{data: "LAST_FINISH"},
{data: "LAST_STATUS"}
],
"columnDefs": [{
"targets": 3,
"data": "LAST_STATUS",
"render": function (data, type, row, meta) {
if (screen.width > 1500) {
return "<div class='text-wrap status-column'>" + data + "</div>";
} else {
return "<div class='text-wrap status-column'>" + data + "</div>";
}
}
}],
dom: '<"toolbar"><"right"B>rt',
buttons: ['excel'],
order: [
[0, 'asc']
]
});
});
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.0.1/css/buttons.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
</head>
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="table-dark">
<tr>
<th>Job ID</th>
<th>Last Start</th>
<th>Last Finish</th>
<th>Last Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Make sure you are including the right extensions for the table. In order for the excel button/export to work. You need to have the Buttons as well as HTML5 Export extensions.
I am using datatables to dynamically render a table on my blade template. I have a series of checkboxes that user can check to show/hide table columns. All of this is working great.
This is what my template looks like:
template.blade.php
<table id="dataTables-report" class="table table-striped table-bordered table-hover">
</table>
Here is what I am using to render the table:
scripts.js
$('#dataTables-report').DataTable({
...
columnDefs: [
{
targets: 0,
title: 'Name',
searchable: true,
data: function (row, type, val, meta) {
// return row.data;
}
},
#if($report->order_date)
{
targets: 1,
title: 'Order Date',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
#if($report->order_number)
{
targets: 2, // could be 1 if order date is not selected
title: 'Order Number',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
...
});
"Order Date" is a checkbox that a user can choose to display on the table. If it is checked, it shows that column. Otherwise it does not.
It is possible that a different column could be selected first and it could be targets: 1. Now if a user checks another box, targets needs to dynamically get set to the next number. In this case: targets: 2.
Each checkbox is stored as it's own column in the database, so I don't think I can do any sort of loop (hence a bunch of if statements). Otherwise, I think something like this would work.
Is there a way to dynamically generate the targets number right in my blade template?
If you're seeking truly dynamic column visibility controlled by checkboxes (as I understood your ultimate goal), it can be done user-end entirely by few lines of jQuery.
In order to do that, you may simply
append source object property of each column as a value attribute to your <input> nodes:
upon change event, find the column that is sourced (using column().dataSrc() method) by the object property that corresponds to clicked checkbox value and adjust that column visibility (using .column().visible() method accordingly:
$('#checkboxWrapper').on('change', '[type="checkbox"]', event => {
let colindex = null;
dataTable.columns().every(function(){
if(this.dataSrc() == $(event.target).val()) colindex = this.index();
});
dataTable.column(colindex).visible($(event.target).prop('checked')).draw();
});
Complete live demo of that concept you may find below:
//sample source data
const dataSrc = [
{id: 1, item: 'apple', cat: 'fruit'},
{id: 2, item: 'carrot', cat: 'vegie'},
{id: 3, item: 'banana', cat: 'fruit'}
];
//extract all unique object keys from data source array
const checkboxes = [...new Set(dataSrc
.map(item => Object.keys(item))
.flat())];
//translate those into <input> nodes HTML
const checkboxesHtml = checkboxes.reduce((inputs, prop) => inputs += `<input type="checkbox" value="${prop}" checked>${prop}</input>`,'');
$('#checkboxWrapper').append(checkboxesHtml);
//initialize datatables
const dataTable = $('#example').DataTable({
data: dataSrc,
dom: 't',
columns: checkboxes.map(prop => ({title: prop, data: prop}))
});
//control columns visibility with checkboxes
$('#checkboxWrapper').on('change', '[type="checkbox"]', event => {
//grab column().index() that corresponds to checkbox value
let colindex = null;
dataTable.columns().every(function(){
if(this.dataSrc() == $(event.target).val()) colindex = this.index();
});
//toggle selected column visibility
dataTable.column(colindex).visible($(event.target).prop('checked')).draw();
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<div id="checkboxWrapper"></div>
<table id="example"></table>
</body>
</html>
Thank you for your suggestions, here is what I came up with as a "quick" solution while I look further into your recommendations.
In my blade template, I created a global variable that I could access within my php.
#section('scripts')
<script>
$(function () {
...
let columnTarget = 0;
...
$('#dataTables-report').DataTable({
...
columnDefs: [
{
targets: columnTarget,
title: 'Name',
searchable: true,
data: function (row, type, val, meta) {
// return row.data;
}
},
#if($report->order_date)
{
targets: ++columnTarget,
title: 'Order Date',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
#if($report->order_number)
{
targets: ++columnTarget,
title: 'Order Number',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
...
</script>
#endsection
This seems to work well; correctly (dynamically) assigning the targets value.
->addColumn('action', function ($floor) {
$action=
#Can("floor-edit"){"
<a class='btn btn-info btn-sm'
href=".route("floor.edit",Crypt::encrypt($floor->id))."><i class='fa fa-edit'></i>
</a>
<button type='button' name='delete' id=".Crypt::encrypt($floor->id)." class='delete btn btn-danger btn-sm'><i class='fa fa-trash'></i></button>
"};
return $action;
})
I am trying full row editor functionality of data-tables.
Editor buttons are not coming.
Without that editor modal will not get displayed.
Inline editor is enabling the columns to edit but its not changing the value of the column.
JS code for data-table.
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "resources/data/data.txt",
table: "#NACH-User-Table",
idSrc: 'id',
fields: [ {
label: "User ID:",
name: "UserID"
}, {
label: "Name:",
name: "Name"
}, {
label: "Email ID:",
name: "emailID"
}, {
label: "Role:",
name: "Role"
}, {
label: "Status:",
name: "Status"
}
]
} );
$('#NACH-User-Table').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this, {
submit: 'allIfChanged'
} );
} );
$('#NACH-User-Table').DataTable({
"ajax" :"resources/data/data.txt",
select: {
style: 'os',
selector: 'td:first-child'
},
ordering: true,
"dom": 'B<"top"fl>rt<"bottom"ip><"clear">',
button: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
"columns": [
{
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ "data": "UserID"},
{ "data": "Name" },
{ "data": "emailID"},
{ "data": "Role"},
{ "data": "Status"}
]
});
});
<table id="NACH-User-Table" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th></th>
<th>UserID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
</tr>
</thead>
</table>
Libraries Included
<script src="./resources/DataTables/jQuery-3.3.1/jquery-3.3.1.min.js"> </script>
<script src="./resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="./resources/DataTables/datatables.min.js"></script>
<script src="./resources/DataTables/DataTables-1.10.18/js/jquery.dataTables.min.js"></script>
<script src="./resources/DataTables/DataTables-1.10.18/js/dataTables.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/dataTables.buttons.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/buttons.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/buttons.print.min.js"></script>
<script src="./resources/DataTables/Responsive-2.2.2/js/dataTables.responsive.min.js"></script>
<script src="./resources/DataTables/Responsive-2.2.2/js/responsive.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Editor-1.8.1/js/dataTables.editor.min.js"></script>
<script src="./resources/DataTables/Editor-1.8.1/js/editor.bootstrap4.min.js"></script>
All the required CSS are Included as well.
I have a DataTable structured like the following:
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
var mainSutable2 =$('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage:{
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status"}
]
});
I am trying to populate this table using the following: Please note MainSutable is another table that has a row that include the object value.
var trackingNotes = {};
trackingNotes = mainSutable.row(this).data().tracking_notes;
//tracikingNotes equals the following
/*
Object {tracking_note: Array[2]}
tracking_note: Array[2]
0:Object
ID: "12345"
comment: "yo"
dt: "2016-06-06 12:50:46.0"
guid: "9999"
status: "1"
1:Object
ID: "12346"
comment: "hey"
dt: "2016-06-08 12:50:46.0"
guid: "9999"
status: "2"
*/
If anyone has any tips of information that could lead me in the right direction, it would be greatly appreciated.
Not sure why it's not working on your side. I've tried replicating the problem but it's working for me and the data is displayed in the DataTable maybe there's an issue with the script references to dataTable.js or maybe you're not calling the binding logic inside the document load.
Copy and paste the example below in a new page and run it, you will see that it works.Figure out what's different in your code compared to mine and I'm sure it will help you solve the problem:
<head runat="server">
<title></title>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
var trackingNotes = [];
var note1 = { ID: "1", comment: "comment1", dt: new Date(), guid:"1", status: "1" };
var note2 = { ID: "2", comment: "comment 2", dt: new Date(), guid: "2", status: "1" };
var note3 = { ID: "3", comment: "comment 3", dt: new Date(), guid: "3", status: "0" };
trackingNotes.push(note1);
trackingNotes.push(note2);
trackingNotes.push(note3);
var mainSutable2 = $('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage: {
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status" }
]
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
Used the data table plugin and try to add the two links Edit and Delete When I click on links it should redirect to some other page.
Please help me on this.. Thanks in advance...
Please find my code snippet:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="#Url.Content("~/Areas/Admin/content/js/bootstrap.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Areas/Admin/content/js/plugins/datatables/jquery.dataTables.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Areas/Admin/content/js/plugins/datatables/dataTables.bootstrap.js")" type="text/javascript"></script>
<div class="box-body table-responsive">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>EmployeeID</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div><!-- /.box-body -->
<script>
var serviceRootUrl = 'http://localhost:49425/Services/MyWcfService.svc/';
$(document).ready(function () {
var oTable = $('#example').dataTable({
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": serviceRootUrl + "EmployeeListResponseCollection",
"aoColumns": [
{ data: "EmployeeID" },
{ data: "Description" },
{
data: null,
"sClass": "center",
"sDefaultContent": 'Edit / Delete'
}
]
});
});
Use the mdata and mrender for the additional field or column to the datatables grid.
Use this snap code inside the script and it should work.
$(document).ready(function () {
var oTable = $('#example').dataTable({
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": serviceRootUrl + "EmployeeListResponseCollection",
"aoColumns": [
{ "mData": "EmployeeID" },
{ "mData": "Description" },
{
"mData": "EmployeeID",
"mRender": function (data, type, full) {
return 'Edit';
}
},
{
"mData": "EmployeeID",
"mRender": function (data, type, full) {
return 'Delete';
}
}
]
});
});