I have the following datatable. Its got a list of columns. Last column is a checkbox.
I want to get list of all rows which has the checkbox ticked? is it possible to get all datatable rows with the checkbox checked? my datatable is like below
$.fn.dataTable.moment('DD.MM.YYYY');
$('#bankReconDataListing tbody').off('click');
RECON_DATATABLE = $('#bankReconDataListing').DataTable({
"language": __DT,
"select": true,
"order": [
[1, "desc"]
],
"searchable": true,
"destroy": true,
"sAjaxSource": '/bankReconciliationGetData?coa=' + coa + '&toDate=' + toDate + '&fromDate=' + fromDate,
"sAjaxDataProp": "",
"bLengthChange": false,
"pageLength": 20,
"aoColumns": [{ //document date : 0
"mDataProp": null,
{ //Document type //5
//balance
"mDataProp": null,
render: function(data, type, row) {
return data.doctype;
}
},
render: function(data, type, row) {
return "<input type='checkbox' name='" + checkBoxName + "' data-tableinput='checkbox' " +
"id='checkBox" + reconJrnlId + "' value='" + reconJrnlId + "' checked='checked' />";
}
}],
"columnDefs": [],
"initComplete": function() {}
});
Give a class name to your checkbox column, say checkboxclass.
Then,
$('.checkboxclass:checked',table.fnGetNodes()).each(function(){
//what you want to do
}
You could attach an event handler to the checkboxes in the table. Whenever a checkbox is clicked, that row gets added to an array. If it's unchecked, you remove it from the array.
This is untested but something like this should work:
let arr = [];
$("#tableDiv tbody").on("click", "input[type='checkbox']", function(e) {
let row = $(this).closest('tr');
// Get row data
let data = table.row(row).data();
if (this.checked) {
// Add to array
arr.push(data);
} else {
arr.splice(arr.indexOf(data), 1);
}
});
#tableDiv is just the table's container. You could use whatever other selector is appropriate depending on your application.
Related
So I'm using Electron.js, datables.net plugin, and child rows.
When I am updating data in the table, child rows stop working until I update data once more, and so on. So child-rows works only once per two data updates. I tried to make a loop where code executes two times, but no success. I got data from Postgres database.
var table = window.$('#table_id').DataTable({
data: data,
select: "single",
retrieve: true,
columns: [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '',
"render": function() {
return '<i class="fa fa-plus-square" aria-hidden="true"></i>';
},
width: "15px"
},
{"data": "fn"},
{"data": "username"},
{"data": "timestamp"},
{"data": "filename"},
{"data": "agent"},
{"data": "job_type"},
{"data": "progress"},
{"data": "status"},
{"data": "priority"},
],
"order": [
[1, 'asc']
]
});
myConsole.log("1")
window.$('#table_id tbody').on('click', 'td.details-control', function() {
var tr = window.$(this).closest('tr');
var tdi = tr.find("i.fa");
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
tdi.first().removeClass('fa-minus-square');
tdi.first().addClass('fa-plus-square');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
tdi.first().removeClass('fa-plus-square');
tdi.first().addClass('fa-minus-square');
}
});
window.$('#table_id').on("user-select", function(e, dt, type, cell, originalEvent) {
if (window.$(cell.node()).hasClass("details-control")) {
e.preventDefault();
}
});
function format(d) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Path:</td>' +
'<td>' + d.path + '</td>' +
'</tr>' +
'<tr>' +
'<td>Message::</td>' +
'<td>' + d.message + '</td>' +
'</tr>' +
'</table>';
}
window.$('#table_id').DataTable().clear().draw();
window.$('#table_id').DataTable().rows.add(data); // Add new data
window.$('#table_id').DataTable().columns.adjust().draw(); // Redraw the DataTable
So, problem was, that each time when i update data and code is running once more, another event listener is created. Code just open and close child row when there is even number of listeners, you just cant see it by eye :)
To fix this issue i added ".off('click')" in my code and now everything works as should.
window.$('#table_id tbody').off('click').on('click', 'td.details-control', function () {
I am using jQuery Datatables, and am working on an inline editing feature. I have been trying to get a green check to show when the record is updated.
Here is the ajax that populates the datatable:
$.ajax({
url: 'api/massEditorSummary.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR)
{
var jsonObject = $.parseJSON(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [
{ "data": "partner_name" },
{ "data": "service" },
{
"data": "forecast",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
{
$(nTd).html("<input type='text' class='form-control editForecast'
id='editForecast' data-uid='"+oData.UID+"' data-editforecast='"+oData.forecast+"'
value='"+oData.forecast+"' style='width:75px; height:30px;' />
<span id='testID' style='display: none;'><i class='fa fa-check' id='updatedIcon' aria-hidden='true'
style='color:green;'> </i></span>");
}
}
],
"stateSave": true,
"autoWidth": false
});
},
error: function(jqHHR, textStatus, errorThrown)
{
// show fail stuff
}
});
If you'll notice in the data column "forecast", I have a span with an ID set to testID. This span includes a font-awesome check icon. I initially set it to display: none.
Now I have this update feature that functions on BLUR event:
$('#example1').on('blur', 'tr > td > .editForecast', function(e)
e.preventDefault();
var uid = $(this).attr('data-uid');
var forecastcurval = $(this).attr('data-editforecast');
var forecastnewval = $(this).val();
var forecastData = '';
$.post('api/inlineEditProcess.php', {uid:uid, forecastcurval:forecastcurval, forecastnewval:forecastnewval}, function(data)
{
forecastData = data;
callForecastFunction(forecastData);
});
function callForecastFunction(forecastData)
{
if(forecastData == "Success")
{
$(this).css('display', 'inline-block'); // this is where I want to show the check
}
else
{
// do fail stuff
}
}
});
You'll see in the callForecastFunction function, if the data that is returned from the process script equals 'success', then show the check.
As mentioned above duplicate id attributes are not allowed. You should fix both the input and span id's. The span id you can base off the UID, for example:
"<span id='" + rowData.UID + "' style='display: none;'><i class='fa fa-check' id='updatedIcon' aria-hidden='true' style='color:green;'> </i></span>");
You can add additional text to make it more unique.
Then change the selector in your callForecastFunction() to select the span based on the UID:
$('#' + uid).css('display', 'inline-block'); // this is where I want to show the check
BTW, it looks like you are missing { in the event handler function:
$('#example1').on('blur', 'tr > td > .editForecast', function(e)
I have a jQuery's datatable which gets filled up with server side data like this:
"columns": [
{
"targets": -1,
"data": "ImageURL",
"name": "Title",
"render": function (data, type, row) {
return '<td><div class="tableimage"><img src="' + data + '"/></div></td>'; //'<td><img src=' + data + '></td>';
}
},
{
"data": "Title",
"name": "Title",
"render": function (data, type, row) {
return '<td>' + data + '</td>';
}
},
{
"data": "CurrentPrice",
"name": "CurrentPrice",
"render": function (data, type, row) {
return '<td>$ ' + data + '</td>';
}
},
]
And this is fine, each column gets generated and rendered in my browser like this:
<tr>
// generated td's here...
<tr>
Now my question here is whether I can generate a custom tr tag with specially added class?
Something like this:
<tr class="myclassNameGoesHere">
</td>
Is this doable via server side data processing & jquery's datatables ?
P.S. I tried something like this:
$(row).addClass("alert-danger");
// or
row.className = "alert-danger";
But neither of these worked... :/
Firstly, you don't need to return td tags in render functions, datatables automatically created td tags for you.
So,
return '<td>' + data + '</td>';
would become
return data;
Now, to answer your question, use createdRow callback provided by datatables.
Like,
$('#example').dataTable( {
"createdRow": function( row, data, dataIndex ) {
$(row).addClass( 'alert-danger' );
}
} );
I have an ajax backed dynatable. At the moment, it works perfectly for tables with known headers prior.
Example:
var tableHeaders = '';
// Generate table headers from some list
$scope.Model.computed.selection_list.map(
function(selection){
column_name = selection.table + "." + selection.column;
tableHeaders += "<th>" + column_name + "</th>";
});
//wipe div hosting the dynatable and reinitialise a table
var table_div = $('#TableDiv');
table_div.empty();
table_div.append('<table id="previewTable" class="table table-condensed table-responsive table-striped table-hover"><thead><tr>' + tableHeaders + '</tr></thead></table>');
var preview_table = $('#previewTable');
console.log("Table wiped");
//initialise the dynatable
preview_table.dynatable({
features: {
perPageSelect: true,
search: false
},
table: {
defaultColumnIdStyle: 'underscore',
headRowSelector:'thead tr',
headRowClass: ''
},
dataset: {
ajax: true,
ajaxUrl: data_url,
ajaxOnLoad: false,
ajaxMethod: 'POST',
records: []
}
});
However, I'd like to have the table headers generated after fetching the records but prior to filling out the rows.
Is this possible?
// Changing via an ajax success event hook doesn't work.
// The table headers change but the records don't bind to the correct column leaving every row as null
preview_table.bind('dynatable:ajax:success', function(e, response){
console.log("Ajax response: " + response) ;
tableHeaders = '';
first_record = response.records[0];
Object.keys(first_record).map(function(column_name){
tableHeaders += "<th>" + column_name + "</th>";
}
)
preview_table.html('<thead><tr>' + tableHeaders + '</tr></thead>')
console.log("headers: " + tableHeaders);
})
I had exactly the same problem and after hours of struggling I came up with this solution:
First, your initial TABLE should look like this:
<table id="my-table">
<thead>
<tr><th></th></tr>
</thead>
<tbody>
</tbody>
</table>
We need the empty TH to prevent the plugin from throwing an error (Couldn't find any columns headers in...), it will be removed later.
Then we use the dynatable:ajax:success to edit the columns as follow:
$("#my-table").one('dynatable:ajax:success', function(e, response){
//Get dynatable
var dynatable = $(this).data('dynatable');
//Remove the empty column
dynatable.domColumns.remove(0);
//Add new columns
var pos = 0;
for(var column in response.records[0]) {
dynatable.domColumns.add($('<th>'+column+'</th>'), pos++);
}
});
Finally, you can initiate the plugin:
$("#my-table").dynatable({
features: {
perPageSelect: true,
search: false
},
table: {
defaultColumnIdStyle: 'underscore',
headRowClass: ''
},
dataset: {
ajax: true,
ajaxUrl: data_url,
ajaxOnLoad: false,
records: []
}
});
Check the following demo, please note that the snippet is not fully functional it throws (SecurityError). Here is a fully working jsfiddle:
var data_url = "https://gist.githubusercontent.com/iRbouh/47a9fb7e5f6a79e0f4b0e7e8a837a825/raw/6adbba47bfbf9453c50f9710f77c71e69f683139/sample-data.json";
var preview_table = $('#my-table');
preview_table.one('dynatable:ajax:success', function(e, response){
//Get dynatable
var dynatable = $(this).data('dynatable');
//Remove init column
dynatable.domColumns.remove(0);
//Add new columns
var pos = 0;
for(var column in response.records[0]) {
dynatable.domColumns.add($('<th>'+column+'</th>'), pos++);
}
});
preview_table.dynatable({
features: {
perPageSelect: true,
search: false
},
table: {
defaultColumnIdStyle: 'underscore',
headRowClass: ''
},
dataset: {
ajax: true,
ajaxUrl: data_url,
ajaxOnLoad: false,
records: []
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdn.rawgit.com/alfajango/jquery-dynatable/master/jquery.dynatable.css" rel="stylesheet"/>
<script src="https://cdn.rawgit.com/alfajango/jquery-dynatable/master/jquery.dynatable.js"></script>
<table id="my-table">
<thead>
<tr><th></th></tr>
</thead>
<tbody>
</tbody>
</table>
I am trying to implement search highlight on data table ( JSON data is coming and filling up the table from serverside through "sAjaxSource"), Please see the below code for details.
search is working by default, BUT highlight is not working at all.
I alerted data of searchTxt+=$('#search_input').val(); alert("txt" + searchTxt);
and alert is displaying search input box text.
Alert for " alert(""+ aData[j]); " displaying "undefined rather than column data and highlight is not working.
Could anyone shed some light on this ?
Thank you,
Sri
jQuery(document).ready(function() {
var oTable = jQuery('#example').dataTable({
"sDom": '<"#table_header"<"#inner_table_header"<"filtertx">fCT<"filterbtn">>>tipl',
"sAjaxSource": ajaxURL,
"bDeferRender": true,
"bProcessing" : true,
"bJQueryUI": true,
"sScrollY": 500,
"aaSorting": [[0, 'desc']],
"aoColumns": [
{ "mData": "name" },
{ "mData": "flag" }
],
"oSearch": {"sSearch": "",
"bSmart": true,
"bRegex": false},
"sPaginationType": "paginate",
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
$(nRow).addClass('clickable');
$(nRow).attr('onClick', "editPopup(" + aData['conditionId'] + ")");
},
"fnDrawCallback": function( oSettings ) {
$(expandWrapper);
}
});
$("#example_filter label").attr("for", "search_input");
$("#example_filter input").attr({
"id": "search_input",
"placeholder" : 'search'
});
oTable.fnSearchHighlighting();
});
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
searchTxt=$('#filter_input input[type="text"]').val();
searchTxt+=$('#search_input').val();
alert("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
alert(""+ aData[j]);
if (aData[j]) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
alert("here");
this.innerHTML = aData[j].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
Wherever the search functionality is and if you are using mData to populate json data, use mData information to retrieve the column data and highlight ( DO NOT use indexes to retrieve column data for search and highlight)
var colProp = oSettings.aoColumns[i].mData;
jQuery('td', nRow).each( function(i) {
/* Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
Only try to highlight if the cell is not empty or null
*/
var colProp = oSettings.aoColumns[i].mData;
if (aData[colProp] !== undefined && aData[colProp] !== null && aData[colProp] !== "") {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
var mapObj = {
'®' : "\u00AE",
'' : "\u2122",
'"' : "\u201C",
' ' : " "
};
aData[colProp] = aData[colProp].replace(/(®)|()|(")|( )/gi, function(matched){
return mapObj[matched];
});
this.innerHTML = aData[colProp].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
else {
this.innerHTML = aData[colProp];
}
}
});
return nRow;
}, 'row-highlight');
return this;