I want to create a dynamic table in bootstrap/jquery, similar to this one
In this example the data is hardcoded, so I thought about changing it with the data that comes from json. Additionally, each row in table has to have a hyperlink added, so my jquery code is as follows:
$('#dataTables-example').DataTable({
responsive: true
});
var data = '[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00","hidden":"21"},
{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00","hidden":"22"}]';
json = JSON.parse(data);
$.each(json, function(i, v) {
$('<tr/>', {
html: [$('<td/>', {
text: v.number
}), $('<td/>', {
text: v.id
}), $('<td/>', {
text: v.price
}), $('<td/>', {
text: v.date
}), $('<td/>', {
html: [
$('<a/>', {
href: '#',
class: 'show-details',
text: 'show details',
data: { id: v.hidden },
click: function() {
var id = $(this).data('id');
console.log(id);
alert(id);
}
})
]
})]
}).appendTo('#dataTables-example tbody')
})
In my html I hardcoded the header of the table:
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>number</th>
<th>id</th>
<th>price</th>
<th>date</th>
<th>show details</th>
<th style="display:none;">hidden identifier</th>
</tr>
</thead>
<tbody></tbody>
</table>
and later on thanks to my script I'm appending rows to the table. Simple as that.
However, as you can see in my fiddle:
http://jsfiddle.net/uo8rc5qL/6/
there is a problem, because since the data is not hardcoded, the table thinks there are no rows and displays the specific message there No data available in table. Also, when I click any column name to sort that data - content disappears, since the table thinks there's nothing to display after sorting...
How can I fix this situation?
This is because you're just adding the data to the table, not the underlying datatable source. The solution is to let datatables handle the loading of the data:
$('#dataTables-example').DataTable({
responsive: true,
"data": JSON.parse(datasrc),
"columns": [
{ data: 'number' },
{data: 'id'},
{data: 'price' },
{ data: "date" },
{
"data": "null",
"defaultContent": "<a>click</a>"
},
{ data: "hidden" }
]
});
Working example: JSFIDDLE
Always go through the API! Insert new rows using table.row.add([..]) instead of the jQuery $('<tr>', {... approach :
$.each(json, function(i, v) {
var row = table.row.add([v.number, v.id, v.price, v.date, '<a>show details</a>']);
table.cells({ row: row.index(), column: 4 }).nodes().to$().find('a')
.attr('href', '#')
.addClass('show-details')
.css('cursor', 'pointer')
.data('id', v.hidden)
.on('click', function() {
var id = $(this).data('id');
console.log(id);
alert(id);
})
table.draw();
})
forked fiddle -> http://jsfiddle.net/2wujw71x/1
Related
I am able to put a button inside each row of data tables but the button doesn't have any function, and I didn't know how to add delete event to that button. can someone help me? hope you give me the demo too ;)
*ps: also, how to put background-color on print, export button. className : red(on TS) and .red{ background-color : red;}(on CSS) didn't work out :/
*another ps : i'm using datatables.net
TS File
products: any = (data as any).default;
ngOnInit(): void {
this.dtOptions = {
ajax: {
url: '',
type: 'GET',
dataType: 'json',
},
columns: [
{
title: 'ID',
data: 'id',
},
{
title: 'Name',
data: 'name',
},
{
title: 'Gender',
data: 'gender',
},
{
title: 'Option',
data: null,
defaultContent:
'<button class="btn-delete type="button">Delete</button>',
targets: -1,
},
],
dom: 'Bfrtip',
buttons: [
{ extend: 'excel', text: 'Export' },
{
text: '<i class="fa fa-files-o"></i>',
action: function (e, dt, node, config) {
dt.ajax.reload();
},
},
{
extend: 'print',
text: 'Print',
},
],
};
}
html
<table
datatable
[dtOptions]="dtOptions"
class="mc row-border hover">
</table>
You can check this Demo
you need to rerender after delete process. You can add button like below and give function to it.
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons">
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td><button class="btn-delete" (click)="deleterow(person)">Remove</button> </td>
</tr>
<tr *ngIf="persons?.length == 0">
<td colspan="4" class="no-data-available">No data!</td>
</tr>
</tbody>
</table>
in component you need rerender function
deleterow(person){
console.log(person);
//here do delete event
const that = this;
this.rerender()
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}
and change your afterinit with
ngAfterViewInit(): void {
this.dtTrigger.next();
}
I have the next Datatable
HTML
<table id="example" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</tfoot>
</table>
JS
$('#example').DataTable({
scrollX: true,
deferRender: true,
"aaData": data.Data,
"columns": [{ data: "ID" },
{ data: "Identificacion" },
{ data: "Nombres" },
{ "data" : null,
"targets" : -1,
"orderable" : false,
"className" : "all",
"width" : "20px",
"render" : function(data, type, full) {
let texto = "";
texto = '<input type="checkbox" id="check_test" value="' + data.ID + '" />';
return texto;
}
}
]
});
I want get value of the selected checkboxes, so i tried this
var aux = [];
aux = $('#example tbody input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
however, this only obtains the values selected from the active page of the pagination datatable
How can I get the value of the selected checkboxes on all pages of datable?
Use $() DataTables API method to retrieve data from all pages, not just first page.
For example:
var $checkboxes = $('#example').DataTable().$('input[type=checkbox]:checked');
I'm trying to add an index column like this example ( https://datatables.net/examples/api/counter_columns.html ), in my table. I try to implement the code from the example to my program, but the results don't appear. How do I add an index column like the example, to my table ?
thank you
Table :
<table id="order_data">
<thead >
<tr >
<th style="text-align:center;" width="21%">Number</th>
<th style="text-align:center;" width="21%">Datetime </th>
<th style="text-align:center;" width="19%">Temp</th>
<th style="text-align:center;" width="21%">Humidity</th>
</tr>
</thead>
</table>
Javascript :
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#order_data').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
title: '<h3 align ="center">Monitoring</h3>',
text: '<i class="fa fa-pencil"></i>',
messageTop: '<p align ="center"><strong>PDF</strong> created by PDFMake with Buttons for DataTables.</p>'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
},
title: 'Monitoring',
titleAttr: 'PDF',
text: 'PDF',
}
],
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
},
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#order_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
The example you're referencing isn't using server side processing. Rather it's assuming a static data source. You have serverSide: true and using an AJAX request to retrieve the data from a source so there are a couple of ways to handle this:
1) Use column render to generate the index value after the data is retrieved:
{
"sName": "Index",
"render": function (data, type, row, meta) {
return meta.row; // This contains the row index
}
}
2.) Add the index value to your data source and retrieve it along with your url:"fetch.php" request. Though this would actually act more like a unique ID and less like row numbering.
There is also an api call for row().index() that you could leverage in a number of ways.
I am working on a project with KnockoutJS where we are pulling data in via Ajax calls and storing them in ko.observableArray. Currently, I have the following table in HTML:
`<table id="gpa">
<tbody data-bind="foreach: gpa">
<tr>
<td data-bind="text: LEVEL"></td>
<td data-bind="text: GPA_TYPE"></td>
<td data-bind="text: HOURS_ATTEMPTED"></td>
<td data-bind="text: HOURS_EARNED"></td>
<td data-bind="text: GPA"></td>
</tr>
</tbody>
</table>`
The JavaScript we have for generating the content via DataTables and the associated options is:
var gpaTarget = {
tableId: 'gpa',
options: {
paging: false,
ordering: false,
info: false,
searching: false,
processing: true,
autoWidth: true
},
columns: [
{ title: 'Level', data: 'LEVEL' },
{ title: 'GPA Type', data: 'GPA_TYPE' },
{ title: 'Hours Attempted', data: 'HOURS_ATTEMPTED' },
{ title: 'Hours Earned', data: 'HOURS_EARNED' },
{ title: 'GPA', data: 'GPA' },
]
}
//Add the DT target for Gpa data
dataTableTargets.push(gpaTarget);
//Initialize datatables for the appropriate DOM elements
if (dataTableTargets.length !== 0) {
$(document).ready(function () {
dataTableTargets.forEach(function (target) {
var table = target.tableId;
var options = target.options;
$('#' + table).DataTable(options);
});
Ideally, the idea from the DataTables.net site's description of how the Column.title feature works is that with a <thead> section, the title property for each column should render a simple column header (see https://datatables.net/reference/option/columns.title for reference.)
However, I have no column headers unless I explicitly declare them in my HTML. As their page says the <thead> element could be non-existent, or that the columns.title option can override the existing <thead> content, I am at a loss for why this is not working as expected.
Does anyone have any insight into what I might be doing incorrectly for this scenario? Any guidance is greatly appreciated.
I am newbie to DataTable. here I am trying to get the of first cell value of a row when I click the viewlink associated with the row, instead of the value I am getting [object object].
heres my code
$(document).ready(function() {
// Delete a record
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData($(this).parents('tr')[0]);
alert(aData);
} );
// DataTables init
var oTable=$('#example').dataTable( {
"sDom": "Tfrtip",
"sAjaxSource": "php/browsers.php",
"aoColumns": [
{ "mData": "browser" },
{ "mData": "engine" },
{ "mData": "platform" },
{ "mData": "grade", "sClass": "center" },
{
"mData": null,
"sClass": "center",
"sDefaultContent": 'view / Delete'
}
]
} );
} );
HTML Table:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th width="30%">Browser</th>
<th width="20%">Rendering engine</th>
<th width="20%">Platform(s)</th>
<th width="14%">CSS grade</th>
<th width="16%">Admin</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Browser</th>
<th>Rendering engine</th>
<th>Platform(s)</th>
<th>CSS grade</th>
<th>Admin</th>
</tr>
</tfoot>
Now when I Click on the view I need to Navigate to another page with the id like
view.php?id=125
Thank you
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData(rowIndex,0);
alert(aData);
} );
From the api docs:
fnGetData
Input parameters:
{int|node}: A TR row node, TD/TH cell node or an integer. If given as a TR node then the data source for the whole row will be returned. If given as a TD/TH cell node then iCol will be automatically calculated and the data for the cell returned. If given as an integer, then this is treated as the aoData internal data index for the row (see fnGetPosition) and the data for that row used.
{int}: Optional column index that you want the data of.
Assuming your first row is your id, would you want to include the links in your dataTable initializer like this?
$(document).ready(function () {
var oTable = $('#example').dataTable({
"aoColumnDefs": [{
"fnRender": function (oObj) {
var id = oObj.aData[0];
var links = [
'View',
'Delete'];
return links.join(' / ');
},
"sClass": "center",
"aTargets": [4]
}, {
"sClass": "center",
"aTargets": [3]
}]
});
});
see: http://jsfiddle.net/9De6w/