Highlight cell data in datatables - php

I'm trying to highlight data in green that is showing positive growth or vice versa.
But i'm facing some issues in Chrome browser while it works fine in Firefox.
Please help me.
$(document).ready(function() {
$('#example').dataTable( {
"ordering": false,
"columnDefs": [
{
"targets": 4,
"createdCell": function (td, cellData, rowData, row, col)
{
if ( cellData.contains("-")) // works fine for Firefox but not for Chrome
$(td).css('color', 'red')
else $(td).css('color', 'green')
}
},
{
"render": function ( data, type, row )
{ return data +' ('+ Math.round(row[4]*10)/10+'%)'; },"targets": 3
}
]
});
} );
</script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css">
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<!--DATATABLES-->
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Metrics</th>
<th>Till Now</th>
<th>Today Trending</th>
<th>Yesterday</th>
<th>DY</th>
<th>5 Day Average</th>
<th>Same Time Last <?php echo date("l");?></th>
<th>Highest</th>
<th>Lowest</th>
<th>Target</th>
<th>Run Rate</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Metrics</th>
<th>Till Now</th>
<th>Today Trending</th>
<th>Yesterday</th>
<th>DY</th>
<th>5 Day Average</th>
<th>Same Time Last <?php echo date("l");?></th>
<th>Highest</th>
<th>Lowest</th>
<th>Target</th>
<th>Run Rate</th>
</tr>
</tfoot>
<tbody>
<?php
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>'.'<strong>'.$row['metric'].'</strong>'.'</td>';
//Till Now
echo '<td>'.number_format($row['Till_Now'], 2, '.', '').'</td>';
//Trending
echo '<td>'.number_format($row['Trending'], 2, '.', '').'</td>';
//Yesterday
echo '<td>'.number_format($row['Yesterday'],2,'.','').'</td>';
//Diff
echo '<td>'.($row['Trending']-$row['Yesterday'])*100/$row['Yesterday'].'</td>';
//5_days_avg
echo '<td>'.number_format($row['5_days_avg'],2,'.','').'</td>';
//STLW
echo '<td>'.number_format($row['stlw'],2,'.','').'</td>';
?>
Any help will be appreciated. Thanks in advance!

you will need to edit the css and program it for chrome. have you tried it?
edit: try double quote marks " where the colors go.

This worked for me, hope it helps :
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"ordering": false,
"columnDefs": [
//Shortening data cell
{
"render": function ( data, type, row )
{ return data +' ('+ Math.round(row[4]*10)/10+'%)'; },"targets": 3
},
//Hide column
{ "visible": false, "targets": [ 4 ] },
//Highlighting data
{
"targets": [3],
"createdCell": function (td, cellData, rowData, row, col){
if ( cellData.indexOf("-")==-1)
$(td).css('color', 'green')
else $(td).css('color', 'red') }
}
]
});
} );

This code syntax usually works in Google Chrome:
$('.status:contains("Paid")').css('color', 'red');
$('.status:contains("Received")').css('color', 'green');

Related

How to resolve DataTables warning: table id=example - Requested unknown parameter 'namaptn' for row 0.?

I want to fetch data from SQL Server, then i send to index.php (With json) to display the data in DataTables. But it give me error like this
DataTables warning: table id=example - Requested unknown parameter 'namaptn' for row 0.
Then I inspect my index.php and I found the json returns this response
{"data" : [ [{"NoSPTA":"096342","TglBerlakuSPTA":"2017-08-07
23:59:59.000","Kdptn":"IA045ZN0HG0","namaptn":"MUNIP
KHUSAINI","TglGawang":"07/08/2017
14:55:33","TglBruto":null,"TglGiling":null,"TglTara":null,"Netto":"0.0","RF":"","Potongan":"0.0"}]]}
This is my code for index.php
<?php
include "db.php";
$obj->tglan=$obj->get_hari();
if (isset($_POST['tanggal2'])) {
$obj->tglan = $_POST['tanggal2'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.js"></script>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/dataTables.bootstrap.css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/datepicker/css/bootstrap-datepicker3.css"/>
</head>
<body>
<center>
<h3>Daftar SPTA<br><?php echo $obj->tanggal("D, j M Y",$obj->tglan);?></h3>
</center>
<left>
<h5>&nbsp&nbsp&nbspLast refreshed : <?php echo $obj->tanggal("D, j M Y",$obj->tglan)." ".date("H:i:s");?></h5>
</left>
<br/>
<form action="viewLaporanUtama2.php" method="POST">
<div class="form-group" >
<label for="tanggal">&nbsp&nbsp&nbspTanggal</label>
<input type="text" name="tanggal1" class="tanggal" id="myText" required/>
<input type="submit" name="enter" value="Cari" class="btn btn-info btn-sm">
</div>
</form>
<div class="container-fluid">
<div class="table-responsive">
<table border = '0' class="table table-striped table-bordered data" id="tabelSpta">
<thead>
<tr>
<th>Nama Petani</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Nama Petani</th>
</tr>
</tfoot>
</table>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var tabel = $('#tabelSpta').DataTable({
"ajax": "database.php",
// "sAjaxSource": "data.js",
"order": [[ 0, 'asc' ]],
"columns": [
{ "data": "namaptn" },
],
});
});
</script>
<!-- <script src="js/jquery-3.2.1.min.js"></script> -->
<script src="assets/js/bootstrap.js"></script>
<script src="assets/datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.tanggal').datepicker({
format: "yyyy-mm-dd",
autoclose:true
});
});
</script>
</html>
And this database.php
<?php
$serverName="192.168.1.250";
$conn = new PDO("sqlsrv:server=$serverName; Database=tebu", "sa", "sukseskan");
$query = "SELECT a.spa AS NoSPTA,
a.tglberlaku as TglBerlakuSPTA,
a.Kdptn,
a.namaptn,
(CONVERT(varchar,b.tgl,103)+' '+ convert( varchar,b.tgl,108))
AS TglGawang,
(CONVERT(varchar,c.tgl,103)+' '+ convert(varchar,c.tgl,108))
AS TglBruto,
(CONVERT(varchar,c.tglgil,103)+' '+ convert(varchar,c.tglgil,108))
AS TglGiling,
(CONVERT(varchar,c.tgltarra,103)+' '+ convert(varchar,c.tgltarra,108))
AS TglTara,
case when tgltarra is not null then
ISNULL(c.bruto, 0) - ISNULL(c.Tara, 0) + 0.001
else ISNULL(c.bruto, 0) end
AS Netto,
isnull(d.RF,'')
as RF, isnull(d.pot,0)
as Potongan
FROM tblSPA a LEFT OUTER JOIN
vtblpos4 d ON a.spa = d.NoSPA LEFT OUTER JOIN
tblbruto c ON a.spa = c.nospa LEFT OUTER JOIN
tblgawang b ON a.spa = b.nospa
where a.tglberlaku>='2017-08-07 00:00:00' and a.tglberlaku<='2017-08-07 23:59:59'
and left(kdptn,5)='IA045'
order by a.spa desc";
// var_dump($query);
$stmt = $conn->prepare($query);
$stmt->execute();
// $hasil = $stmt->fetchAll(PDO::FETCH_ASSOC);
$jsonResult = '{"data" : [ ';
$i = 0;
while ($data=$stmt->fetchAll(PDO::FETCH_ASSOC)) {
if($i != 0){
$jsonResult .=',';
}
$jsonResult .=json_encode($data);
$i++;
}
$jsonResult .= ']}';
// var_dump($jsonResult);
echo $jsonResult;
?>
I don't know what's wrong with my json, i already type the parameter like the database. How i can solve this problem?
Looks like you have an array within an array. This Datatables doc shows an example of what your JSON should look like:
https://datatables.net/manual/data/#Objects
I think you need to remove the inner array and it should display your "namaptn" field.

How to search in a HTML table that does not generate any td's and such?

I've created a table based on the http://www.jtable.org template, my table, and most of the functionality is up and running, however I run into a problem when I want to include a search bar to filter tables results as I type. The problem I believe lies in the fact that most tables I've created using php have created the actual html table in the code so td's and tr's for example, and the search functionality would key off of matching these terms.
Currently however my table is being generated on the front end, without the actual HTML content in the back end, so I am unable to search. Is there any method I can use to search this table with this code, maybe using server side processing, or something else I'm unaware of?
This is the code I'm using:
<html>
<title> title </title>
<head>
<link href="themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="scripts/jtable/themes/metro/darkgray/jtable.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="scripts/jtable/jquery.jtable.js" type="text/javascript"></script>
</head>
<body>
<div class="filtering">
<body>
<input type="text" style="background-color: #e6ffff;" placeholder="Search Any Column" size="70" id="search";/>
</body>
<div id="PeopleTableContainer" style="width: relative;" ></div>
<img src="Sharks-2-Trans-30-150623-2.png" width="150" height="43" style="float:bottom-right; opacity: 10;">
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'ICS Central',
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'ISO_Name ASC', //Set default sorting
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
//selectOnRowClick: false, //Enable this to only select using checkboxes
actions: {
listAction: 'PersonActions2.php?action=list',
createAction: 'PersonActions2.php?action=create',
updateAction: 'PersonActions2.php?action=update',
deleteAction: 'PersonActions2.php?action=delete'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
ISO_Name: {
title: 'ISO Name',
width: '5%'
},
ICS_Defect: {
title: 'Defect #',
width: '5%'
},
Abstract: {
title: 'Abstract',
width: '30%'
},
problem_description: {
title: 'Problem Description',
width: '30%'
},
fix_description: {
title: 'Fix Description',
width: '30%'
},
levels_approved: {
title: 'Levels Approved',
width: '30%'
},
reboot_required: {
title: 'Reboot Required?',
width: '30%'
},
reapplied_after_ccl: {
title: 'Reapplied After CCL?',
width: '30%'
},
reapplied_after_hmc_rebuild: {
title: 'Reapplied After HMC Rebuild?',
width: '30%'
},
bundle_fix_cmvc: {
title: 'Bundle Fix CMVC',
width: '30%'
}
},
//Register to selectionChanged event to hanlde events
selectionChanged: function () {
//Get all selected rows
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#SelectedRowList').empty();
if ($selectedRows.length > 0) {
//Show selected rows
$selectedRows.each(function () {
var record = $(this).data('record');
$('#SelectedRowList').append(
'<b>ISO_Name</b>: ' + record.ISO_Name +
'<br /><b>Abstract</b>:' + record.Abstract + '<br /><br />'
);
});
} else {
//No rows selected
$('#SelectedRowList').append('No row selected! Select rows to see here...');
}
},
// rowInserted: function (event, data) {
// if (data.record.ISO_Name.indexOf('Add_Info_HB_v1.0.iso') >= 0) {
// $('#PeopleTableContainer').jtable('selectRows', data.row);
//}
//}
});
//Load student list from server
$('#PeopleTableContainer').jtable('load');
//Delete selected students
$('#DeleteAllButton').button().click(function () {
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#PeopleTableContainer').jtable('deleteRows', $selectedRows);
});
});
</script>
</body>
</html>
I use a search text field and filter the result on keyUp, but that is not client side filtering. It makes the ajax call to the list action and uses a variable searchname to do its filtering. We use Hibernate and have a line of code that filters from the DB like: " obj.name like '%searchname%' "
<body>
<div class="filtering">
Name: <input type="text" id="search"/>
</div>
<body>
...
...
<script type="text/javascript">
$(document).ready(function () {
...
$('#search').keyup(function(){
$('#PeopleTableContainer').jtable('load', {searchname: $(this).val()});
});
}

Populate DataTables Ajax Json object from PHP using multi tables

In my project I'm using DataTables to display my data, which is retrieved from an PHP echo json_encode. The PHP page is a script that returns JSON:
{
"sig1_re": [
{
"Ticket_RT": 716771,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 50,
"Res_LigneCoupee": "short",
"Ticket_fils": 152321,
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716760,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 67,
"Res_LigneCoupee": "open",
"Ticket_fils": "",
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
],
"bad_nd": [
{
"Ticket_RT": 716620,
"Numero_ND": 236598741,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716577,
"Numero_ND": 565231583,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
]
}
In my first attempt I had one JS file for each table in my HTLM and that works great, but I repeat the same code a lot and call the JSON echo each time, so I decided to regroup all my code in one JS file.
I managed to export almost all the tables options but I'm having trouble defining some variables; one is hideFromExport: I need to only copy the values from the first columns when I click on "COPY" button. The second problem is with oTable which I use to delete the row. I would like to set these two variables to be compatible with all my tables. (in my below example I use only two tables but in the actual project I have more).
Live Example: http://live.datatables.net/peceqofo/1/edit
Code:
<!DOCTYPE html>
<html>
<head>
<link href="https://raw.githubusercontent.com/twbs/bootstrap/master/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Cable_de_renvoi</th>
<th>Longueur_de_ligne_</th>
<th>Res_LigneCoupee</th>
<th>Ticket_fils RT</th>
<th>Gamot_DateFermeture</th>
<th>Numero_ND</th>
<th>Gamot_DateFermeture</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Numero_ND</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {};
$.ajax({
url: "http://www.json-generator.com/api/json/get/bUHEbjuIoi?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var hideFromExport = [1, 2, 3]; /*<--- How i can custom this for each table individually ?? */
var options = {
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [{ /*<--- How i can custom this for each table individually ?? */
extend: 'copyHtml5',
exportOptions: {
columns: function(idx, data, node) {
var isVisible = table.column(idx).visible();
var isNotForExport = $.inArray(idx, hideFromExport) !== -1;
return isVisible && !isNotForExport ? true : false;
}
}
},
'excelHtml5', 'csvHtml5', 'pdfHtml5'
],
language: {
url: "https://cdn.datatables.net/plug-ins/1.10.12/i18n/French.json",
buttons: {
copy: 'Copier Tickets',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 },
{ "title": "Titre 9", "targets": 8 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "title": "Titre 03", "targets": 2 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
var oTable = $('#tableA').DataTable(); /*<--- How i can custom this for each table individually ?? */
$('#tableA').on('click', 'a.delete', function (e) {
oTable.row($(this).parents('tr')).remove().draw();
});
// Permet de réduire les commentaires et ajouter tooltip
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
Solution :
Well after a lot of research i found an solution for the commun button options, now that works good ! Then I have added a button that will delete your selected row(s).
I hope this code will help more guys in the same situation like me !
Enjoy :)
Code :
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/bfm.css">
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {}; // get the json object array from php
$.ajax({
url: "http://www.json-generator.com/api/json/get/bTKebXDGdK?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var buttonCommon = { // set default export column 0 (first column)
exportOptions: {
columns:[0]
}
};
var options = { // set options for tables
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [
$.extend( true, {}, buttonCommon, {
header: false,
extend: 'copyHtml5'
}),
'excelHtml5', 'csvHtml5', 'pdfHtml5',
{
text: 'Delete',
action: function ( e, dt, node, config ) { // function to delete selected rows on click button
dt.data().rows('.selected').remove().draw( false );
}
}
],
language: {
url: "json/French.json",
buttons: {
copy: 'Copy',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Difference_de_date" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) } // call function to render + tooltip
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
$('#tableA tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
$('#tableB tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
// Function to delimit render + tootil
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
I would suggest to keep the tables separate with attributes. And if you would like to add extra columns and buttons in data tables. You can achieve that using following approach.
Add an extra column for action.
On fnRowCallback method add specific class to the action column.
Example of click on action:
jQuery('#datatable tbody').on('click', 'td.action', function () {
//call custom method to format the data inside td.action column.
data = {
'id': $(this).attr('cour_id')
};
tr.after(format(data)).show();
});
It will create action button for each row with specific row ids and attributes and won't conflict with each other.
Hope it will help!

How to show pictures in a table using jQuery DataTables

Is that possible that I can show my URL images in data-table? I returning my data in array as it shown here in my code and returning the URL image with...
Before I knew the DataTables I was using the default table an put my table in <img src=""> so how can I use it here?
<?php
class basket_report{
function show_basket_report(){
$connect_mysql= #mysql_connect($server,$username,$passwor) or die ("Connection Failed!");
$mysql_db=mysql_select_db("GP15",$connect_mysql) or die ("Could not Connect to Database");
$query = "SELECT * FROM reportBasket where notifyEmployee='1'";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$objects= array();
while($rows=mysql_fetch_array($result))
{
$objects[]= $rows;
}
$data_set = "[";
$count_rows = count($objects);
$count = 1;
foreach($objects as $object){
$data_set .= "['". $object['reportID'] ."', '". $object['email'] ."', '". $object['date'] ."', '". $object['time'] ."', '". $object['BasketID'] ."', '". $object['notifyEmployee'] ."','". $object['replyedPhoto'] ."']";
if($count != $count_rows){
$data_set .= ",";
$count++;
}
}
$data_set .= "]";
return $data_set;
}
?>
<html>
<head>
<script src="js/jquery-1.11.1.js"></script>
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="DataTables-1.10.7/media/css/jquery.dataTables.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="DataTables-1.10.7/media/js/jquery.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="DataTables-1.10.7/media/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#table_id').dataTable( {
"data": dataSet,
"columns": [
{ "title": "report_id" },
{ "title": "email" },
{ "title": "date" },
{ "title": "time"},
{ "title": "basket_id"},
{ "title": "notify_Employee"},
{ "title": "replyed_photo"}
]
} );
} );
</script>
</head>
<body>
<table id="table_id" class="display">
</table>
<?php
include('class_report_basket.php');
$basket_report = new basket_report();
?>
<script>
var dataSet= <?php echo $basket_report->show_basket_report(); ?>;
</script>
</body>
</html>
You can use columns.render option to define callback function to render cell content based on its data.
$('#example').DataTable({
"ajax": {
url: "/test/0",
},
"columns": [
{ "data": 0 },
{
"data": 1,
"orderable": false,
"sortable": false,
"render": function (data, type, row, meta){
// If data will be displayed
if(type === "display"){
return '<img src="' + data + '">';
// Otherwise, if search/filtering is performed
} else {
return data;
}
}
}
]
});
Note that if you use columns to define your columns, you must have an entry in the array for every single column that you have in your table (these can be null if you don't which to specify any options). Alternatively, you can use columnDefs to target specific columns.
See the example below for code and demonstration. Please note, that I'm using jQuery Mockjax plug-in just for the sake of demonstrating Ajax request, it's not needed for production code.
$(document).ready(function () {
// AJAX emulation for demonstration only
$.mockjax({
url: '/test/0',
responseTime: 200,
responseText: {
"data": [
[ "100x150", "http://placehold.it/100x150" ],
[ "200x150", "http://placehold.it/200x150" ],
[ "300x150", "http://placehold.it/300x150" ]
]
}
});
$('#example').DataTable({
"ajax": {
url: "/test/0",
},
"columns": [
{ "data": 0 },
{
"data": 1,
"orderable": false,
"sortable": false,
"render": function (data, type, row, meta){
if(type === "display"){
return '<img src="' + data + '">';
} else {
return data;
}
}
}
]
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Picture</th>
</tr>
</thead>
</table>
</body>
</html>

Range of numbers in a column with Tablesorter in wordpress

I intended to use Tablesorter plugin to sort table in my wordpress theme. At one of my table column I have a range of values (i.e. 8-10, 5-12 and so on). On this column the sorting doesnt work. I saw the solution example in stackoverflow. I tried to implement this but with no luck. In general sorting works on my table, however it gives incorrect results on that column.
Here is my header file where I include scripts:
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery-latest.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.tablesorter.widgets.js"></script>
Here is my table
<table cellspacing='0' id="posts-table"> <!-- cellspacing='0' is important, must stay -->
<!-- Table Header -->
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>Col5</th>
<th>Col6</th>
</tr>
</thead>
<!-- Table Header -->
<!-- Table Body -->
<?php /* Start the Loop */
$i = 1;?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
$val1 = get_post_meta($post->ID, 'x-value', true);
$post_categories = get_the_category();
$categories_by_id = array();
foreach ( $post_categories as $category ) {
$categories_by_id[$category->cat_ID] = $category;
}
foreach ( $post_categories as $category ) {
unset( $categories_by_id[$category->category_parent] );
}
echo '<tr>';
echo '<td class="align-center">'; echo $i++; echo'</td>';
echo '<td>'; echo end($categories_by_id)->cat_name; echo'</td>';
echo '<td>'; echo the_title(); echo'</td>';
echo '<td class="align-center">'; echo $val1; echo'</td>';
echo '<td class="align-center">'; echo $val1; echo'</td>';
echo '<td class="align-center">'; echo $val1; echo'</td>';
echo'</tr>';
?>
<?php endwhile; ?>
<!-- Table Body -->
</table>
And this is initialization of tablesorter
$(document).ready(function()
{
$("#posts-table").tablesorter({
theme: 'blue',
sortList: [[1,0]],
widthFixed: true,
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_functions: {
1 : function(e, n, f, i) {
var parts = e.split('-'),
val = parseFloat(f),
min = parseFloat(parts[0]),
max = parseFloat(parts[1] || 999); // default max = 999
return val >= min && val <= max;
}
},
filter_formatter : {
1 : function($cell, indx){
return $.tablesorter.filterFormatter.uiSlider( $cell, indx, {
values : 0,
min : 0,
max : 60,
delayed : false,
exactMatch: false,
valueToHeader : false
});
}
}
}
});
}
);
Any thoughts why this isnt working? Sorry if it sounds stupid. Cheers :)
The filter_formatter code is used with a separate filter formatter file. I don't think it's necessary, or it might be the cause of the code not working for you.
Remove that block of code and see if it fixes your sorting issues (demo):
$(function () {
$('table').tablesorter({
theme: 'blue',
sortList: [[1, 0]],
widthFixed: true,
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_functions: {
1: function (e, n, f, i) {
var parts = e.split('-'),
val = parseFloat(f),
min = parseFloat(parts[0]),
max = parseFloat(parts[1] || 999); // default max = 999
return val >= min && val <= max;
}
}
}
});
});

Categories