This question already has answers here:
how to use Jquery Datatables Ellipsis renderer for template field link button?
(1 answer)
Solution for Ellipsis - Jquery + Bootstrap + Datatables
(1 answer)
DataTables how to cut string and add (...) and put the full string in tooltip
(2 answers)
Closed 4 years ago.
I'm working on a CI project that requires the use of datatables, some of the content in the database has a large number of characters and i want to limit those to 150, i have tried to use the examples that are posted in the datatables site without luck, just to be clear i didnĀ“t made this full script, I took it from somewhere else.
This is my script
<script type="text/javascript">
$(document).ready(function() {
var st = $('#search_type').val();
var table = $('#consulta-table').DataTable({
"dom" : "<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"processing": false,
"pagingType" : "full_numbers",
"pageLength" : 15,
"serverSide": true,
"orderMulti": false,
"order": [
<?php if($default_order != null) : ?>
[<?php echo $default_order ?>, "<?php echo $default_order_type ?>"]
<?php else : ?>
[6, "desc"]
<?php endif; ?>
],
"columns": [
null,
null,
null,
null,
null,
{ "orderable": false },
{ "orderable": false },
null,
{ "orderable": false }
],
"ajax": {
url : "<?php echo site_url("consultas/consultas_page/" . $page . "/" . $catid) ?>",
type : 'GET',
data : function ( d ) {
d.search_type = $('#search_type').val();
}
},
"drawCallback": function(settings, json) {
$('[data-toggle="tooltip"]').tooltip();
}
});
$('#form-search-input').on('keyup change', function () {
table.search(this.value).draw();
});
} );
function change_search(search)
{
var options = [
"search-like",
"search-exact",
"title-exact",
"title2-exact",
"title3-exact",
"title4-exact",
"title5-exact",
"title6-exact",
];
set_search_icon(options[search], options);
$('#search_type').val(search);
$( "#form-search-input" ).trigger( "change" );
}
function set_search_icon(icon, options)
{
for(var i = 0; i<options.length;i++) {
if(options[i] == icon) {
$('#' + icon).fadeIn(10);
} else {
$('#' + options[i]).fadeOut(10);
}
}
}
</script>
Any help is appreciated
Thanks in advance
Have you tried this yet? It is the official plugin offered by people under the datatables.net community. You just need to follow the instruction there and you're good to go.
Simply download/copy the plugin script then, follow this sample code
$('#myTable').DataTable( {
columnDefs: [ {
targets: 0,
render: $.fn.dataTable.render.ellipsis()
} ]} );
Related
I have a data table which is loaded within a script like so:
<script>
function table() {
$.ajax({
url: 'tables/winnertable-all.php',
type: 'get',
data: { name: '<?php echo $name ?>', Type: '<?php echo $Type ?>' },
success: function(response){
$('.winnertable').html(response);
$('#newtable').DataTable();
}
});
}
table();
setInterval(table, 3600000);
table();
setInterval(table, 3600000);
$(document).ready(function() {
$('#newtable').DataTable();
} );
</script>
I would like to add default ordering to the first column, i have found this code on the data tables website as an example:
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 3, "desc" ]]
} );
} );
I would like to implement this in my code, however i cannot get the table to load after adding the line.
I have tried:
<script>
function table() {
$.ajax({
url: 'tables/winnertable-all.php',
type: 'get',
data: { name: '<?php echo $name ?>', Type: '<?php echo $Type ?>' },
success: function(response){
$('.winnertable').html(response);
$('#newtable').DataTable();
"order": [[ 1, "desc" ]];
}
});
}
table();
setInterval(table, 3600000);
table();
setInterval(table, 3600000);
$(document).ready(function() {
$('#newtable').DataTable();
"order": [[ 1, "desc" ]];
} );
</script>
I know their is a problem with my syntax implementation however i have tried various different things and cannot get it to work.
Generally, If you want to reinitialise a DataTable in order to change its basic settings, you need to use the destroy flag.
However, in your case I would just add the desired order-settings to defaults
$.extend( true, $.fn.dataTable.defaults, {
order: [[ 3, "desc" ]]
})
If you do that upfront, on pageload, all tables will have order: [[ 3, "desc" ]] as default. If you for some reason not want to alter the defaults, you can simply take advantage of the API, that surprise surprise have an order method
var table = $('#newtable').DataTable()
table.order( [[ 3, "desc" ]] ).draw()
I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );
You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/
It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.
I'm new to dataTables concept in jQuery. I'm trying my best to learn and work with dataTables. My requirement is to show most recent recent records when the checkbox is checked. I'm using jQuery datatable.
Below is my sample code:
$(document).ready(function() {
initTable();
} );
function initTable(){
oTable = $('#table_id').dataTable({
"aaSorting": [[ 12, "desc" ]],
"oLanguage": {
"sProcessing": "<span style='font-size:20px; color:blue;'>Loading...<span/>",
"sLengthMenu": 'Display <select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'<option value="30">30</option>'+
'<option value="40">40</option>'+
'<option value="50">50</option>'+
'</select> records'
},
"bProcessing": true,
"bServerSide": true,
"asStripeClasses": [ 'evenrow', 'oddrow' ],
"sAjaxSource": "spreadData.do?method=searchSpreadData",
"fnServerParams": function ( aoData )
{
aoData.push({"name":"searchCriteria.toDate", "value": $('#todateId').attr("value") });
aoData.push( { "name":"searchCriteria.SerialNumber", "value":$('#serialNumberId').attr("value")});
aoData.push( { "name":"searchCriteria.formatId", "value": $('#formatId').attr("value")});
aoData.push( { "name":"searchCriteria.fromDate", "value": $('#fromdateId').attr("value")});
aoData.push( { "name":"searchCriteria.doSearch", "value": $('#doSearchId').attr("value")});
aoData.push( { "name":"searchCriteria.spreadpercentage", "value": $('#spreadPercentage').attr("value")});
},
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [ 0 ] },
{ "bVisible": false, "aTargets": [ 11 ] }
],
"bJQueryUI": true,
"bFilter": false
});
$('#displayRecentRecords').click( function() {
alert("step1");
oTable.fnDraw();
} );
}
//The below function is not getting called when checkbox is checked from UI.
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
alert("step2");
if($("#displayRecentRecords").is(':checked')){
return true;
}
return !aData[11];
}
);
Show Recent Records:<input type="checkbox" id="displayRecentRecords"/>
Please see my sample code above. When I run the application and select the checkbox step1 alertbox is shown but step2 alert box is not getting called.
Please suggest what are the changes to be done to the above code to call last mentioned datatable function (alertbox which prints step2).
I'm new to dataTable concepts in jQuery. I read the documentation and came across few examples. Please find the JSFiddle : http://jsfiddle.net/9jf2k53p/135/.
Please suggest what modifications to be done in JSFiddle to show the most recent records when the checkbox is checked.
Appreciate the help. Thanks.
Change this line:
$.fn.dataTableExt.afnFiltering.push(
to this:
$oTable.fn.dataTableExt.afnFiltering.push(
OR (not sure which will work in your case):
$oTable.dataTableExt.afnFiltering.push(
You need to define the table as part of this function. That's what the oTable is for, as you defined this variable on the 6th line of your code above.
SOLUTION
You need to define custom filtering function before initializing the table.
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ){
// ... skipped ...
}
);
var oTable = $('#table_id').dataTable({
// ... skipped ...
});
DEMO
See this jsFiddle for code and demonstration.
My datatable loads perfectly except the columndefs do not work.
Anybody got a clue?
Please help. I just want to add a click event to every cell in column 1. I get no errors either.
It works in this example on the end column...https://datatables.net/examples/ajax/null_data_source.html
var table = $mytable.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
});
Found a great post on stack overflow that really helped.
and changed it to suit me this is the post Edit jQuery Datatable fields
And here is what I have working for me. I was concentrating too much on the API and less on just Jquery. The trick was execute the jquery after "drawCallback":
Credit to #Jeromy French
var table = $spr_cnt_tbl.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
"drawCallback": function( settings ) {
apply_label();
}
});
var apply_label=function(){
$spr_cnt_tbl.find("td:nth-child(2)").not(':has(.label)').each(function(){
if( this.innerHTML===""){
$(this).wrapInner("<button class=btn btn-success id='sel_img' type='button'>Select Image</button>");
}
else {
$(this).wrapInner('<span class="label label-success"></span>');
}
});
};
});
});
I am using the DataTables jQuery plugin and I am having a problem when I want to insert a hide details option on my existing table, this is how this option should look like: LINK
My problem is that table head is inserted correctly but I am not seeing a table column with plus sign to expand and see details.
Here is my code and as you can see it is almost incidental as it is on the link that I provided.
The code:
/* Formating function for row details */
function fnFormatDetails ( oTable, nTr )
{
var aData = oTable.fnGetData( nTr );
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
sOut += '<tr><td>Rendering engine:</td><td>'+aData[1]+' '+aData[4]+'</td></tr>';
sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
sOut += '</table>';
return sOut;
}
$(document).ready(function() {
/*
* Insert a 'details' column to the table
*/
var nCloneTh = document.createElement( 'th' );
var nCloneTd = document.createElement( 'td' );
nCloneTd.innerHTML = '<img src="../images/details_open.png">';
nCloneTd.className = "center";
$('#jphit thead tr').each( function () {
this.insertBefore( nCloneTh, this.childNodes[0] );
} );
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd.cloneNode( true ), this.childNodes[0] );
} );
var oTable=$('#jphit').dataTable( {
"sDom": 'T,C<"clear">lfrtip',
"oTableTools": {
"sSwfPath": "swf/copy_csv_xls_pdf.swf"
},
"oColVis": {
"buttonText": "Extend table",
"activate": "mouseover"
},
"aoColumnDefs": [
{ //"bVisible": false, "aTargets": [ 0 ],
"bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[1,'asc']],
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "full_numbers",
"sScrollY": "350px",
"bDeferRender": true,
"sAjaxSource": "increment_table.php"
} );
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#jphit tbody td img').live('click', function () {
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
this.src = "../images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
this.src = "../images/details_close.png";
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
} );
} );
As I was debugging I realized that this code is processed but its not drawing what it should draw:
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd.cloneNode( true ), this.childNodes[0] );
} );
Any idea what might went wrong with my code? And if someone is using this plugin can you please help and share your experience?
EDIT:
This is the picture that I am getting. It should be shifted one spot to the right and in that empty column I should have a pic for opening a details
EDIT2:
I have tried to use this code with data that I wrote manually inside the table and it is working perfectly.
I have tired to put the code inside the fnDrawCallback function but then I have 2 headers as my table is drawing twice.
How to use this with sAjaxSource?
var oTable = $('#jphit').dataTable( {
"sDom": 'T,C<"clear">lfrtip',
"oTableTools": {
"sSwfPath": "swf/copy_csv_xls_pdf.swf"
},
"oColVis": {
"buttonText": "Extend table",
"activate": "mouseover"
},
"aoColumnDefs": [
{ //"bVisible": false, "aTargets": [ 0 , 2 ] ,
"bSortable": false, "aTargets": [ 0 ] }
],
"bProcessing": true,
//"bServerSide": true,
"sPaginationType": "full_numbers",
"sScrollY": "350px",
"bDeferRender": true,
//"sAjaxSource": "live_table.php",
"fnDrawCallback": function( oSettings ) {
var nCloneTh = document.createElement( 'th' );
var nCloneTd = document.createElement( 'td' );
nCloneTd.innerHTML = '<img src="images/details_open.png" style="width:25px; height:25px;">';
nCloneTd.className = "center";
$('#jphit thead tr').each( function () {
this.insertBefore( nCloneTh, this.childNodes[0] );
} );
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd, this.childNodes[0] );
} );
}
} );
The problem here is that table renders data based on data from response. I suppose that there is aaData array where 0 index is filled with value, which is inserted in the first column as expected.
You can use this approach http://datatables.net/release-datatables/examples/ajax/null_data_source.html
In your case you could change aoColumnDefs option to:
"aoColumnDefs": [ {
"bSortable": false, mData : null, "aTargets": [ 0 ]
}],
EDIT Override fnServerData
The other idea I have is to override fnServerData callback, to change datasource as you need.
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function(jsonData) {
//Here you need to shift jsonData aoData array values to right
//to add [0] index in all values.
//I have no possibility to test it today:( but hope it will help you
//and Then you need to call fnCallback(jsonData) with changed jsonData
for (var data in jsonData["aoData"]) {
jsonData["aoData"][data].unshift(0);
}
fnCallback(jsonData);
}
} );
}
Hope it helps.