How to use index column for multiple tables with a single statement in datatable js? - javascript

I'm using datatable js for 2 tables in a single page.
HTML
<!-- Table#1 -->
<table class="dataTable">
<thead>
<tr>
<td>#</td>
<td>col1</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>val1</td>
</tr>
<tr>
<td></td>
<td>val2</td>
</tr>
<tr>
<td></td>
<td>val3</td>
</tr>
</tbody>
</table>
<!-- Table#2 -->
<table class="dataTable">
<thead>
<tr>
<td>#</td>
<td>col1</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>val1</td>
</tr>
<tr>
<td></td>
<td>val2</td>
</tr>
<tr>
<td></td>
<td>val3</td>
</tr>
</tbody>
</table>
Javascript
$(document).ready(function() {
var t = $('table.dataTable').DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
} );
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
It's showing the index column only in first table.
How can I display it?
I know it's possible by using two different id on the tables. But, in that case I've to copy the javascript code again. If I want to use another table need to copy it once more.
Is there any way to use it for all tables by using the javascript code once?

Presumably you want the two tables to be numbered independently of each other.
If so, then this in the event handler should refer to whichever table the event relates to, and t.table(this) will select "this" table from the tables held in t.
$(document).ready(function() {
var t = $('table.dataTable').DataTable({
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}],
"order": [[1, 'asc']]
});
t.on('order.dt search.dt', function () {
t.table(this).column(0, {search:'applied', order:'applied'}).nodes().each(function (cell, i) {
cell.innerHTML = i+1;
});
}).draw();
});

Try this,
Use the .eq() method in order to access a jQuery object by its index. And eq indices start from 0.
var numTables = $(table).length
$(document).ready(function() {
for(var i =0; i < numTables; i++){
var t = $('table.dataTable').eq(i).DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
} );
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
}
});

Related

Space between data when exporting excel file from datatables

I have this bug on my export file using Datatables. There are some unnecessary space between the data.
<script>
$(document).ready(function () {
$('.dataTablesWExport').DataTable({
dom: 'Bfrtip',
buttons: [{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
"order": []
});
});
</script>
Screeshot of the export file
https://i.stack.imgur.com/X4gah.png
You can use a row function to control which rows are exported (the rows with data) and which are not (the blank rows).
Example
Assume I have the following data in my table:
<table id="myTable" class="display nowrap dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adélaïde Fleury</td>
<td>System Architect</td>
<td>Paris</td>
</tr>
<tr>
<td>John Smith</td>
<td>Accountant</td>
<td>London</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Tokyo</td>
</tr>
</tbody>
</table>
My DataTable object is defined like this:
$('#myTable').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [ 0, 1 ], // just for my demo
rows: function ( idx, data, node ) {
return data[0];
}
}
}
]
} );
This is displayed as follows:
It uses a rows function to test each row. If the first cell in the row (data[0]) has data in it, then the row will be exported to Excel. But if the cell is blank, empty, or null, the row will not be exported:
How It Works
The row function returns a value of true or false for each row in the DataTable. JavaScript will therefore treat a non-blank value in data[0] as truthy - and therefore that row is returned.
So, return data[0] is just a more compact way of writing this:
if ( data[0].length > 0 ) {
return true;
} else {
return false;
}
Data Arrays vs Data Objects
My source data was taken directly from the HTML table, so it was provided as arrays of data (one array for each row): [ 'John Smith', 'Accountant' ]. This is why I used data[0] to check the contents of the first cell in each row.
If my data had been sourced from a JSON object, it may have looked different, for example:
{
"name": "John Smith",
"position": "Accountant"
},
{
...
}
In this case, data[0] would not work. I would need to use data.name instead.

php product comparison table

I'm working on a product comparison table. I want to add a td in every last child in all tr. I want to display all products in vertical in a table. The product comparison table is made using php.
This is the code:
<thead id="table_row">
<tr id="h_td">
<th></th>
<th>product 2</th>
<th>product 3</th>
<th>product 2</th>
<th>add</th>
</tr>
</thead>
<tbody id="pro_table">
<tr class="visible-xs " aria-hidden="true" id="collapse" >
<td colspan="5" >Fature 1</td>
</tr>
<tr id="h_td">
<td>Fature 1</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 2</td>
</tr>
<tr id="h_td">
<td>Fature 2</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 3</td>
</tr>
<tr id="h_td">
<td>Fature 3</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 4</td>
</tr>
<tr id="h_td">
<td>Fature 4</td>
</tr>
</tbody>
<?php
$con = mysqli_connect("localhost","root","","COMPARES");
$b_title = array();
$sql="SELECT * from brands";
$run=mysqli_query($con,$sql);
$num_row=mysqli_num_rows($run);
while($row=mysqli_fetch_assoc($run)){
$rows[] = $row;
foreach($rows as $row){
$b_title =$row['brand_id'];
$b_title =$row['brand_title'];
$data =' '.$b_title.' ';
}
}
?>
<script type="text/javascript">
var tables = document.getElementsByTagName('tbody');
var table = tables[tables.length - 1];
var rows = table.rows;
for(var i = 0, td; i < rows.length; i++ ){
td = document.createElement('td');
td.appendChild(document.createTextNode("<?php echo data ?>"));
rows[i].insertBefore(td, rows[i].lastChild);
}
</script>
This is the result:
Why write you own table when much better options out there already exist?
Using jQuery # http://jquery.com/ and DataTables # https://datatables.net/, you can easily have dynamic column adding capability -- Check out this fiddle for an example: http://jsfiddle.net/4nil/zq7j97c4/10/--
var data_table, row_num, col_num, row_cell, col_cell, iter=0;
var cols = [
{ "mDataProp": "Field1"},
{ "mDataProp": "Field2" },
{ "mDataProp": "Field3" },
{ "mDataProp": "Field4" }
];
var colDef = [{aTargets: [0], sTitle: "Date"},
{aTargets: [1], sTitle: "Number"},
{aTargets: [2], sTitle: "FName"},
{aTargets: [3], sTitle: "LName"},
];
//Get stored data from HTML table element
var results = [{
Field1: "2011/04/23",
Field2: 8,
Field3: "Adam",
Field4: "Den"},
{
Field1: "2011/03/25",
Field2: 6,
Field3: "Honey",
Field4: "Singh"}
];
function initDT(){
//Construct the measurement table
data_table = $('#example').dataTable({
"bJQueryUI": true,
//"sPaginationType": "full_numbers",
//"bProcessing": true,
"bDeferRender": true,
"bInfo" : false,
"bDestroy" : true,
"bFilter" : false,
"bPagination" : false,
"aaData": results,
"aoColumns": cols,
"aoColumnDefs": colDef
});
attachTableClickEventHandlers();
}
initDT();
function attachTableClickEventHandlers(){
//row/column indexing is zero based
$("#example thead tr th").click(function() {    
col_num = parseInt( $(this).index() );
console.log("column_num ="+ col_num );  
});
$("#example tbody tr td").click(function() {    
col_cell = parseInt( $(this).index() );
row_cell = parseInt( $(this).parent().index() );   
console.log("Row_num =" + row_cell + "  ,  column_num ="+ col_cell );
});
};
$("#btnAddRow").click(function(){
//adding/removing row from datatable datasource
var record = {
"Field1": "2011/04/23",
"Field2": '8',
"Field3": "tom",
"Field4": "jerry"};
data_table.fnDestroy();
results.push(record);
//results.pop();
initDT();
$('#example').dataTable().makeEditable({
sUpdateURL: function(value, settings) {
console.log(value);
}});
});
$('#btnAddCol').click(function () {
var oSettings = data_table.fnSettings();
$("#example thead tr th").eq(col_num).after('<th></th>');
cols.push( {"mDataProp": "Field5"} );
colDef.push({aTargets: [4], sTitle: "Message"});
results[0].Field5 = "Msg1";
results[1].Field5 = "Msg2";
data_table.fnDestroy();
data_table.oApi._fnAddColumn(oSettings,null);
initDT();
});
EDIT:
If your content is going to be static, there are plenty of "comparison table" examples, using Bootstrap found here: https://bootsnipp.com/tags/table

Unable to display data using jQuery datatables, AJAX and JSON

I'm having a problem displaying my data on my jQuery DataTable using AJAX. I'm using the library from datatables.net. I've tried packaging the JSON in many different formats and nothing is working. I've also messed around with the 'columns' section, interchanging 'title' and 'data.' I only have one event to display for now, but the bottom of the table shows something crazy like 4,000 entries. Here is my code:
<script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/api/EventsApi/GetAll",
"dataSrc": ""
},
columns: [
{ title: "Title" },
{ title: "Template" },
{ title: "Capacity" },
{ title: "Boarding Location" },
{ title: "Status" },
{ title: "Edit / Delete" }
//{ "data": "title" },
//{ "data": "eventTemplateID" },
//{ "data": "locomotive.capacity" },
//{ "data": "boardingLocationStart.city" },
//{ "data": "status" },
//{ "data": "status" }
]
});
});
<div class="title-content">#ViewBag.Title</div>
<div id="dataTable">
<table id="myTable" class="table table-hover" style="text-align: center;">
<tbody id="tBody">
<!-- Table body data goes here -->
</tbody>
</table>
</div>
Here is the JSON that's being returned from the AJAX call:
{"data":[{"tripEventID":1,"extraDetails":"this train has special details","eventName":"ZombieTrainEventName ","departureDate":"\/Date(1443715200000)\/","returnDate":"\/Date(1443718800000)\/","eventCapacityOveride":100,"eventTemplateID":3,"title":"The Zombie Train ","companyID":1,"description":"description of zombie train ride ","boardingClosed":30,"status":1,"boardingLocationStart":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationStartTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnFrom":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"allowFlexableReturnDate":false,"product":[],"productBundle":[{"bundleID":10,"companyID":1,"displayName":" Pumkin Bundle copy Test","price":0.0100,"tax":0.0200,"productList":[]}],"locomotive":{"trainID":1,"companyID":1,"title":"Skunk_Steam ","type":1,"description":"Steam locomotive ","capacity":998,"status":0},"media":{"mediaID":1,"companyID":1,"hero":[],"gallery":[{"mediaDetailID":6,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":null,"url":null},{"mediaDetailID":7,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":"path6","url":"url6"},{"mediaDetailID":8,"formatTypeID":2,"fileName":"testimage7.txt","order":1,"path":"path7","url":"url7"}],"inside":[{"mediaDetailID":1,"formatTypeID":1,"fileName":"testimage.txt","order":1,"path":null,"url":null},{"mediaDetailID":2,"formatTypeID":1,"fileName":"testimage2.txt","order":1,"path":null,"url":null},{"mediaDetailID":3,"formatTypeID":1,"fileName":"testimage3.txt","order":1,"path":null,"url":null}]},"duration":15,"isExclusive":false,"timeAtDestination":45,"isOneWay":false}]}
Like I said, I've tried repackaging the JSON as nested objects and arrays with nothing working. Am I missing something obvious? Any help is appreciated, thank you!
You have to name the columns in your js like the json index keys like this:
$(document).ready(function() {
$('#myTable').DataTable( {
"ajax": "path/to/your/file.json",
"columns": [
{ "data": "title" },
{ "data": "eventTemplateID" },
{ "data": "eventCapacityOveride" },
{ "data": "boardingLocationStart.streetAddress" },
{ "data": "status" },
{ "data": null }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
Note that you can define custom data in tables with the columnDefs option.
And than edit your HTML with something like this:
<table id="myTable" class="table table-hover" style="text-align: center;">
<thead>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</tfoot>
</table>
Here you can find a working fiddle

Cannot destroy() using "Yet Another DataTables Column Filter" plugin

I'm using DataTables and YADCF to filter a table.
At some point, I need to temporarily unbind both plugins from my table and later bind them again. If I don't use YADCF, I can destroy the datatable and initialise it again. However, when I use YADCF, the filter part of the table isn't destroyed.
HTML:
Create | Destroy
<table id="mytable" class="results table table-striped">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>152</td>
<td>13</td>
<td>154</td>
</tr>
<tr>
<td>1762</td>
<td>1873</td>
<td>1874</td>
</tr>
<tr>
<td>124</td>
<td>1343</td>
<td>1124</td>
</tr>
</tbody>
</table>
JS without YADCF JSFIDDLE:
var oTable = $('table');
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false,
});
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
});
JS with YADCF JSFIDDLE:
var oTable = $('table');
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false,
});
// Add YADCF
oTable.yadcf([{
column_number: 1,
filter_type: 'range_number',
ignore_char: 'm'
}, {
column_number: 2,
filter_type: 'text',
filter_default_label: ' '
},
]);
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
});
Can anyone suggest how to destroy the YADCF filter too?
So, this is actually a bug present.
Issue Submitted | Workaround JSFiddle
JS:
var oTable = $('table');
var first = true;
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false
});
if (first) {
first = false;
// Add YADCF
oTable.yadcf([{
column_number: 1,
filter_type: 'range_number',
ignore_char: 'm'
}, {
column_number: 2,
filter_type: 'text',
filter_default_label: ' '
} ]);
} else {
oTable.find('thead').find('[id^=yadcf-filter-wrapper-table]').each(function (i, v) {
var cloned = $(this).clone(true);
console.log( $(this) );
$(this).closest('th').append( cloned );
$(this).remove();
oTable.find('.DataTables_sort_wrapper').css('display', 'inline-block');
});
oTable.find('[id^=yadcf]').show();
}
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
oTable.off();
oTable.find('[id^=yadcf]').hide();
oTable = $('table');
});
$('#add-row').click(function (e) {
e.preventDefault();
$('table').append('<tr><td>' + getRandom() + '</td><td>' + getRandom() + '</td><td>' + getRandom() + '</td></tr>');
});
function getRandom() {
return parseInt(10000 * Math.random(), 10);
}
try the below:
$('#destroy').click(function (e) {
e.preventDefault();
oTable.Destroy();
oTable.attr('class', '');
});

Datatables with rowGrouping unable to hide columns

The JS:
$(document).ready(function() {
// $( "#dashboard_container" ).tabs();
$('#listings').dataTable({
"bRetrieve": true,
"aoColumns":
[
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
]
}).rowGrouping({
iGroupingColumnIndex: 1,
sGroupingColumnSortDirection: "asc",
iGroupingOrderByColumnIndex: 0,
bExpandableGrouping: true,
bExpandSingleGroup: true,
iExpandGroupOffset: -1
});
});
The HTML:
<table class="datatable" id="listings">
<thead>
<tr>
<th>Group Index</th><th>Group Display Name</th>
<th>Organization</th>
<th>Volumes</th>
<th>Read (MB/s)</th>
<th>Write (MB/s)</th>
<th>Volume Size (GB)</th>
<th>My Cost (USD)</th>
<th>Comments</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody>
<tr>
<td>0</td><td>Artful Scientific</td>
<td>Something Co.</td>
<td>information</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>$0</td>
<td><a class="btn small icon i_preview comment_edit_button" rel="1" title="edit or view comment">View</a></td>
</tr>
</tbody>
</table>
</div>
The problem:
I am able to successfully do the row groupings and it works fine, however I have a need where I need to hide 2 of the columns to certain roles. As well as hide an additional column which would be the Equivlent of the "Organization" column which the grouping uses. However from the above JS you can see I have tried hiding all columns just to see if any would actually hide in my last ditch effort before coming here. No matter which ones all or one none will hide. Anyone know a work around for this? As I need the columns to remain but hidden to the actual view
hide column using this command and first parameter is index of the column and
second parameter is visibilty
fnSetColumnVis( 1, false );

Categories

Resources