How do I add an index column to Datatable? - javascript

I want to add a row number for each row in my data table. I am using plugin from http://datatables.net The page which tells how to add the index is http://datatables.net/release-datatables/examples/api/counter_column.html
... however I don't know how to actually implement it to make it work. I know extremely little about jquery / javascript which would help in this case. I don't know where to put this code to make it work (if it helps i am also using Ruby on Rails)
The initialization code is:
jQuery ->
$('#staffs').dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
}

Here is an example from datatables.net site DataTables row numbers example
$(document).ready(function() {
$('#staffs').dataTable( {
sPaginationType: "full_numbers",
bJQueryUI: true,
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
},
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[ 1, 'asc' ]]
} );
} );
Regarding your SyntaxError: reserved word "function" on line 4 (in /home/ubuntu/ruby/scoreboard/app/assets/javascripts/staffs.js.coffee)' error
take a look at this rails, getting syntax error with coffee script

jquery is javascript. You need to add the code Daniel pasted between
<script language="javascript">
and
</script>
tags.

I am working with latest dataTable 1.10 and gem rails datatable and ajx
for
finding the DataTable row number(Serial Number)
def data
outer = []
records.each_with_index do |record, index|
outer << [
# comma separated list of the values for each cell of a table row
# example: record.attribute,
index + 1 + params[:start].to_i,
record.company_name,
record.id,
record.patients.count,
record.revenue_total
]
end
outer
end

Related

DataTables - Sorting not working after content update

I'm using DataTables (version 1.10.18) and I'm updating rows and its content via jQuery.
My table is initalized with this code:
$(".summary").append(tableContent);
var otable = $('.summary').DataTable({
initComplete: function () {
this.api().columns([0, 1, 2, 3]).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
"pageLength": records_per_page,
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.16/i18n/Italian.json"
},
"order": [[0, 'desc']],
"ordering": true,
"scrollX": true,
"scrollY":"50vh",
"searching":false,
"info":false,
"paging": false
});
Then I've an input field that searches in a SharePoint list (via Rest API). So I make an AJAX call, I get the response from SharePoint web service and I prepare HTML code with new data (some data returned from web services needs to be modified). Finally I update the table content using this code:
var otable = $('.summary).DataTable();
otable.clear().draw();
$(".dataTables_scrollBody>.summary").append(newContent);
otable.rows().invalidate().draw();
newContent is something like:
newContent = "<tbody><tr><td>content</td><td>content</td></tr></tbody>";
Content is updating correctly and sorting arrows are visible in the table header, they are also changing their own active status (desc or asc) but content is not sorted.
I've tried a lot of solutions found online but no one is working for me. In the content update section I'm also adding rows using .append() method.
Is there a way to fix this?
i would suggest, instead of appending the row, you should use the https://datatables.net/reference/api/row.add() add method which is exposed by datatable api. This will automatically apply all the initial settings to new added row.

Formatting server side jQuery Datatable

I am trying to format the front end look of my jQuery DataTable
I currently have it looking like this https://imgur.com/a/PPgL48Y
I need the repeating items in each row to be remove for example in the first row there are 2 Owner 1's. I only want to display a single Owner 1 in that row.
The other issue is in row 2, Url1 is followed by a comma then Url 2 but i want
Url1
Url2
In the row, so removing the comma and adding a new line in that col
My data is being collected via server side processing
My current jQuery code
<script type="text/javascript" >
$('#result').DataTable({
"serverSide":true,
"filter": false,
"orderMulti": false,
"ajax": "DetailedSearch?handler=ServerSideDataTable",
"columns":[
{"data": "location",
"render": function(data,type,row){
return row.location;
}
},
{"data": "contactAndRole",
"render": function(data,type,row){
return data.key + " - " + data.value;
}},
{"data": "server", "sortable": "false"},
{"data": "urls",
"render": function(data,type,row){
return row.urls + '<br>';
}
}
],
rowGroup:{
dataSrc:'appName'
}
});
</script>
Can i add some html elements? like a br after each url, or can the table be constructed with pure html then passed onto data tables to output?
I've looked into the HTML templates, and standalone documentation on the data tables website but nothing seems to be helpful.
The commas for the url's array are because of the default way arrays are processed to strings to be printed into the html in the dom
You could join() them yourself using a <br> separator instead
return row.urls.join('<br/>')

JS Datatables - filtering table from combo box in header

I have the following datatable which uses the js datatable plugin from https://datatables.net/
The datatable is set using the following JS:
$(document).ready(function () {
$('#tracerTable').DataTable({
"bInfo": false,
"order": [[2, "desc"]], //order by date created
"aoColumnDefs": [
{ aTargets: [3], "bSortable": false },
{ aTargets: [4], "bSortable": false },
{ aTargets: [5], "bSortable": false }
]
});
}
Question:
Is it possible to update the JS to allow me to filter on the 'Type' column using a dropdown with tickbox options within in the table header (just like the filter option in excel - see image below). I would want this for selecting Water and Oil Tracers, but not showing Gas tracers.
If this is not possible within the datatable plugin, can anyone suggest a plugin which would provide this functionality?
Make use of the bootstrap-select plugin, append it to the header of your DataTables by targeting the desired column (in your case 1), get the checked values, join it with | (the or operand) then use search API.
var table = $('#example').DataTable({
initComplete: function() {
this.api().columns([1]).every(function() {
var column = this;
var select = $('<select class="selectpicker" data-show-content="false" data-none-selected-text="Position" multiple><option value="" >Show All</option></select>')
.appendTo($(column.header()).empty())//use $(column.footer() to append it to the table footer instead
.on('changed.bs.select', function(e) {
var val = $(this).val();
var fVal = val.join("|")
column
.search(fVal, true, false)
.draw();
}); //select
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
}); //column.data
}); //this.api
} //initComplete
});
Fiddle for more details, I suggest moving the filter function on the footer as clicking the dropdown button on the table header will sort the table.

Datatables data search and highlight with jmHighligh limit to one column (solution at the end)

I'm working with Datatables.
Datatables allows you to have one single search box included in plug in, but with help of many of your posts I was able to make a single column search for each column (I know there was a plugin of Datatables for I was unable to make it work for me).
After this I've tried to implement the code to obtain search results highlighted in table after search (again with Datatable highlight plugin). I was able to do this, but than I wanted to add another highlight plugin for each search box I've created.
I was also able to deal with this metter (using jquery.jmHighlight.min.js code) but I've found 2 different problems:
I was unable to limit to a single column the highlighting
I was unable to avoid highlight disappear clicking on next search box.
Here is the part of code I'm using:
<script>
function filterGlobal () {
$('#example').DataTable().search(
$('#global_filter').val()
).draw();
}
function filterColumn ( i ) {
$('#example').DataTable().column( i ).search(
$('#col'+i+'_filter').val()
).draw();
var keyword = $('#col'+i+'_filter').val(); // this is to retrieve what have been inserted in search box called "colNUMOFCOLUMNfilter"
$('#col'+i+'_filter td:nth-child(1)').jmRemoveHighlight(); //one of my test to limit search to a single column (the same as search box)
$('#col'+i+'_filter td:nth-child(1)').jmHighlight(keyword); //one of my test to limit search to a single column (the same as search box)
//I've also tried with: $('input.column_filter').on( 'keyup click', jmRemoveHighlight()); $('input.column_filter').on( 'keyup click', jmHighlight(keyword));]
}
$(document).ready(function() {
[...]
var table = $('#example').DataTable( {
[...]
"ajax": {
[...]
// HIGHLIGHT SEARCH (from Datatable that works only with global filter)
"searchHighlight": true,
[...]
$('input.global_filter').on( 'keyup click', function () {
filterGlobal();
});
$('input.column_filter').on( 'keyup click', function () {
filterColumn( $(this).parents('tr').attr('data-column') );
});
[...]
</script>
So my problems are:
limit to a single column the highlighting. When I use the code above ($('#example tbody').jmRemoveHighlight()/jmHighlight(keyword)) it works but all the words matching with the input are highlighted.
Avoid highlight disappear clicking on next search box. With that code, when I've something highlighted due to search box input, when I click on another search box, the highlighted word return normal, even deactivating jmRemoveHighlight().
It would be great to be able to add one search result highlighted to the next one, until you don't reset everything, limiting results to a single column each search box (only first search box would be a general search into the whole table).
UPDATE v. 0.1
That's true, I'm not really good with javascript and jquery, but I thought this would have worked, what's wrong?
$(document).ready(function() {
var table = $('#example').DataTable( {
[all vars of plugin]
} );
//many listeners like
// LINE FOR COL REORDER
new $.fn.dataTable.ColReorder( table );
// LINE FOR ENLIGHT SELECTED ROW
$('#example tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
// HERE I've tried mine
// TEST TEST
$("input[name='keyword']").on("keyup", function () {
window.alert("test");
var datacol = table.column( 1 ).data(); //func of datatables to retrieve column data
highilightMe( datacol ); //my function
});
// TEST TEST
[... many others working listeners]
});
//My function
function highilightMe( datacol ) {
window.alert("HEY I AM HERE!");
// Read keyword
var keyword = $("input[name='keyword']").val(); //input for test highlight
//var table = $('#example').DataTable();
//var data = table.column( 0 ).data();
//Highlight the keyword inside the context
//$("#example, td, row").eq(1).jmRemoveHighlight();
//$("#example, td, row").eq(1).jmHighlight(keyword);
//window.alert();
$("#example", datacol).jmRemoveHighlight();
$("#example", datacol).jmHighilight(keyword);
}
But it stills doesn't work and not even WINDOWS.ALERT works... so it means function isn't well called, but why...?
P.S. what's really strange is that using $("#example, td, row").eq(1).jmRemoveHighlight() I was able to highlight just one CELL but in another TABLE (mine with datatables on is called #example).
UPDATE v. 0.2
In order to understand what wasn't working and considering my little knowledge of jQuery, I've rebuilt a test page to check what wasn't working.
Here follow the code of that page that uses datatables. I was able to recover also data column, but I'm not able to use that var (an array of data) as #container to limit highlight function.
Here is full code:
[...]
<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/fixedheader/3.0.0/js/dataTables.fixedHeader.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/colreorder/1.2.0/js/dataTables.colReorder.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/rowreorder/1.0.0/js/dataTables.rowReorder.min.js"></script>
<title>Untitled Document</title>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="js/dataTables.searchHighlight.min.js"></script>
<script type="text/javascript" src="js/jquery.highlight.js"></script>
<link rel="stylesheet" type="text/css" href="css/dataTables.searchHighlight.css">
<script type="text/javascript" src="js/jquery.jmHighlight.min.js"> </script>
</head>
<body>
<br />
<div class="title"><u>Search module</u></div><br />
<br />
<table id="example" class="show" id="show">
<thead>
<tr>
<th>Market</th>
<th>Curr</th>
<th>Prods<br />(Qn)</th>
<th>Quality</th>
<th>Seller<br />(type)</th>
<th>Type</th>
<th>Stock</th>
<th>Price<br />(curr)</th>
<th>GOLD<br />Curr<br />change</th>
<th>Price<br />(GOLD)</th>
<th>Vat<br />tax</th>
<th>Loc. Seller<br />price</th>
<th>Imp.<br />Tax</th>
<th>Int. Seller<br />price</th>
<th>Link</th>
<th>Serv</th>
<th>Time Rec</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<br />
</tbody>
</table>
<br />
<hr width="95%" align="center">
<br />
<div class="col-xs-6">
<span>Type in a keyword:</span>
<input type="text" name="keyword" id="keyword" placeholder="Lorem ipsum..."> //I uses this for TESTING
</div>
<br />
<hr width="95%" align="center">
<br />
<script>
function test ( keyword ) {
var col = $('#example').DataTable();
var datac = col.column( 0 ).data();
console.log( datac );
//$.inArray(keyword,[datac]);
//$.inArray(jmHighlight( keyword ),[datac]);
//$("#example", datacol).jmRemoveHighlight();
//$("#example", datacol).jmHighilight(keyword);
$datac.jmRemoveHighlight(); //this return an error about finding datac var...
$datac.jmHighlight( keyword );
}
$(document).ready(function() {
// TEST TEST
$("#keyword").on("keyup", function () {
var keyword = $("#keyword").val();
test( keyword );
});
// TEST TEST
var serverChoice = "server";
var table = $('#example').DataTable( {
"processing": true,
"rowReorder": true,
"lengthMenu": [ [30, 60, 90, 120, 150, -1], [30, 60, 90, 120, 150, "All"] ],
"language": {
"loadingRecords": "Please wait - loading..."
},
select: {
style: 'multi'
},
"ajax": {
"url": "server_processing_prods.php?serverch="+serverChoice,
"dataSrc": "demo",
},
//CHANGE COLOR OF FONT ON DATA
"createdRow": function ( row, data, index ) {
// if ( data[7].replace(/[\$,]/g, '') * 1 > 10 ) {
if ( (data[14]) = "Evening Record" ) {
$('td', row).eq(14).addClass('evening_record');
} else if ( (data[14]) = "Night Record" ) {
$('td', row).eq(14).addClass('night_record');
} else if ( (data[14]) = "Afernoon Record" ) {
$('td', row).eq(14).addClass('afternoon_record');
} else if ( (data[14]) = "Morning Record" ) {
$('td', row).eq(14).addClass('morning_record');
}
},
// HIGHLIGHT SEARCH
//"searchHighlight": true,
//this is to set the link
"columnDefs": [
{
"targets": [0],
"render": function ( data ) {
return '<center><b><font size="1">' + data + '</font></b></center>';
}
},
{
"targets": [1],
"render": function ( data ) {
return '<center><font size="1">' + data + '<br /><div class="sprite ' + data + '"></div></font></center>';
}
},
{
"targets": [2],
"render": function ( data, type, row ) {
return '<center><b><font size="1">'+ data +'</b><i> Q'+ row[3] +'</font></i></center>';
}
},
{
"targets": [3, 9, 11, 13],
"render": function ( data ) {
return '<font size="1"><center>' + data + '</center></font>';
}
},
{
"targets": [4],
"render": function ( data, type, row ) {
return '<center><font size="1">'+ data +'<br><i>('+ row[5] +')</font></i></center>';
}
},
{
"targets": [8],
"render": function ( data ) {
return '<font size="1"><i><center>' + data + '</center></i></font>';
}
},
{
"targets": [10, 12],
"render": function ( data ) {
return '<font size="1"><i><center>' + data + '%</center></i></font>';
}
},
{
"targets": [14],
"render": function ( data ) {
return '<center><font color="#fff400" size="1">go to market</font></center>';
}
},
{
"targets": [6, 7, 15],
"render": function ( data, type, row ) {
return '<center><font size="1">'+ data +'</font></center>';
}
},
{
"targets": [16],
"render": function ( data, type, row ) {
return '<center><i><font size="1">'+ data +'</font></i></center>';
}
},
{ "visible": false, "targets": [ 3, 5 ] }
]
} );
});
</script>
</body>
</html>
Here is the code.
Follows console result.
SOLUTION v. 1.0
And here we go. As usual solution is quite easier if correctly interpreted.
What was wrong in my idea is that I was trying to limit jmhighlight using the DATA (alias the data array) that would have fulfilled table column, but what I needed to do was to limit highlight function only to a particular column identified with a particular id.
So the easiest way was this: Datatables let you define how any single column of your table will be
"columnDefs": [
{
"targets": [0],
"render": function ( data ) {
return '<center><div id="country"><b><font size="1">' + data + '</font></b></div></center>';
}
},
so the easiest way to limit highlight function was to tell the function to highlight words in id.TABLE, part.of.TABLE and id.COLUMN.
Adding a div id to each column with different names, I was able to determine function container easily like this:
$("#example tbody #country").jmRemoveHighlight();
$("#example tbody #country").jmHighlight(keyword);
That's it. Probably it was exactly what rafaelcastrocouto was suggesting me, but I was unable to understand it.
Congratulations that you have solved the issue for yourself. However, just for others having the same issue: I just added an example in the documentation that shows you how to search and highlight column specific inside a DataTable-table.
Update: There's now a new plugin to handle search highlighting for DataTables: datatables.mark.js.

Datatable fnCellRender doesn't render

I am trying to render some fields before exporting to excel in my function I am doing like this;
"tableTools": {
"sSwfPath": "assets/global/plugins/data-tables/tabletools/swf/copy_csv_xls_pdf.swf",
"aButtons": [ {
"sExtends": "xls",
"sButtonText": "Excel",
"fnCellRender":function(sValue,iColumn,nTr,iDataIndex){
console.log(sValue);
//console.log($(sValue));
return sValue;
}
}, {
"sExtends": "print",
"sButtonText": lang.L_PRINT,
"sInfo": lang.L_PRINT_DESC,
"sMessage": "Metrics"
}]
}
So when I uncomment
console.log($(sValue));
it returns just first and second column which doesn't include any html tag inside. But when it finds a value that have html tag it stops.
ex - this gets the valu
<td class=" sorting_1">201408</td>
this doesn't
<span style="text-align:right;display:block;width:100%">121.25</span>
How can I fix it ?
To troubleshoot this I found it much easier to just write the data into the CSV and see the format so I could then choose how to parse.
When you use the fnCellRender property TableTools will not do any parsing of the HTML anymore. I would expect that you would see the raw data in the console window some of which would be HTML I assume and others just values.
When it's HTML you can use JQuery to extract the values or a regular expression. E.g
if ($(sValue).prop("checked")) {
return "TRUE";
} else {
return "FALSE";
}
or in your case
return $(sValue).val();
Some research I used:
TableTools background and good discussion with links
TableTools Reference API

Categories

Resources