Jquery Datatable update cell text value and colour - javascript

I have a datatable which has ajax sourced data.
I have some function which validates the data in table cell by cell and changes cell color to red if validation failed. also having an column with no data initially and updates its data later. I set rowId as ip_address to identify that row based on ip.
Now i want to update the empty cell whose ip matches rowid in table.
I tried $("#devices_table td:nth-child(3)").text('hi');
which updates all rows for 3rd column, but i want to update only one row matching that rowId.
tbl1 = $('#devices_table').dataTable({
autoWidth: false,
scrollX: true,
scrollY: 400,
paging: false,
select:{ style: 'multi' },
info: false, // This will prevent showing message 'Showing 1 of N rows'
serverSide: true,
aoColumns: [ { title: "Result", data:'Result', defaultContent: '', name: 'Result'},
{ title: "IP Address",data: "IP_Address", name:'IP_Address'}, ],
fnRowCallback: function( nRow, aData, iDisplayIndex ) {
$('td', nRow).attr('nowrap','nowrap');
return nRow;
}, // This is for content wrap in column
ajax: "/get_device_table", // call for data
rowId: 'IP_Address',
this is my table defination.
tbl1.fnUpdate('abc' , $('tr#192.168.30.20'), 0 );
$("#devices_table").children().children()'192.168.30.20'].children[0].innerHTML = "Hi";
$('#devices_table tr:eq('+rowid+') td:eq(0)').text('ChangedText');
and these are few things which I tried but didnt work for me.
I am new to datatables and jquery, so this code can have stupid mistakes too.. please correct me if any. Thanks in advance.

Solved.
Issue was due to setting ip address as id
changed . in ip to - and added className to column and it worked.
and following code of line,
aoColumns: [
{ title:"Result", data:'Result', defaultContent:'',className:'result'},
{ title: "IP Address",data: "IP_Address", className:'IP_Address'}, ]
$('#192-168-32-24').find('td.result').html('hi')

Related

Ext Js. Several values in dataindex

I got values in JSON and want to add several values in dataindex. How I can do this?
This works perfectly
columns: [
{
header: "Records",
dataIndex: time,
sortable: true,
},
];
But this example doesn't work
columns: [
{
header: "Records",
dataIndex: time + value + value1,
sortable: true,
},
];
Column property dataIndex should be a string that is the name of the field in the model definition, see documentation. To add different values from the model and display the result in a grid column, either use a calculated field and put the calculated field's name to dataIndex, or create a custom renderer function for the column and add the values there.

getData does not reflect changes made on the Tabulator table

I am new to JavaScript and Tabulator, I am stuck at this place, your help is appreciated.
I have loaded the data on the tabulator table and making few changes to it (add new column, deleting column etc.), these changes are reflected on the table but when I use table.getData() updated data is not reflected (old data is reflected). I need this to use some other places. Where am I going wrong?
Here is the sample code.
tabulatorTable = new Tabulator("#dfTable", {
selectable:true,
data:dataJson,
layout:"fitColumns", //fit columns to width of table
responsiveLayout:"hide", //hide columns that dont fit on the table
tooltips:true, //show tool tips on cells
addRowPos:"top", //when adding a new row, add it to the top of
//table
history:true, //allow undo and redo actions on the table
pagination:"local", //paginate the data
paginationSize:20,
movableColumns:true, //allow column order to be changed
resizableRows:true, //allow row order to be changed
columns:[
{title:"YearsExperience", field:"YearsExperience", editor:"number"},
{title:"Salary", field:"Salary", sorter:"number"}
]
});
tabulatorTable.addColumn({formatter:"rownum", title:"id"}); **// Adding new column to the table**
console.log(tabulatorTable.getData()); **// Does not reflect the newly added column**
Expected Json file to contain added column data (title - "id")
You can't modify data just by adding a column to the grid. Additionally, the column you added is a "rownum" formatter and is not bound to a field, so what key would it know to add? You will need to explicitly modify the data on the table.
See here: http://tabulator.info/docs/4.2/update
Solved it see snippet
tabulatorTable.addColumn({
formatter: "rownum",
field: "id",
title: "id"
});
const dataJson = [{
'YearsExperience': 2,
'Salary': 40000
},
{
'YearsExperience': 3,
'Salary': 50000
},
]
const tabulatorTable = new Tabulator("#dfTable", {
selectable: true,
data: dataJson,
layout: "fitColumns", //fit columns to width of table
responsiveLayout: "hide", //hide columns that dont fit on the table
tooltips: true, //show tool tips on cells
addRowPos: "top", //when adding a new row, add it to the top of
//table
history: true, //allow undo and redo actions on the table
pagination: "local", //paginate the data
paginationSize: 20,
movableColumns: true, //allow column order to be changed
resizableRows: true, //allow row order to be changed
columns: [{
title: "YearsExperience",
field: "YearsExperience",
editor: "number"
},
{
title: "Salary",
field: "Salary",
sorter: "number"
}
]
});
tabulatorTable.addColumn({
formatter: "rownum",
field: "id",
title: "id"
}); // Adding new column to the table**
console.log(tabulatorTable.getData()); // Does not reflect the newly added column**
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.2.7/css/tabulator.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.2.7/js/tabulator.min.js"></script>
<div id="dfTable"></div>

Make edit link on datatable with multiple column values and global search on single/custom column(s)

How to create an edit link with function having multiple parameter from the data columns returned from ajax.
I read about the render callback but it only gets one column value & I need 2.
I need something like the following pseudo code.
"columnDefs": [ {
"targets": [0,1],
"data": "0,1",
"render": function ( data, type, full, meta ) {
return ``
}
} ]
As I'm disabling global search on all column except one. I cannot use the above code that use targets property. I don't know how to achieve this, please guide.
Edit: Complete code
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{ "searchable": false, "targets": [ 0,2,3,4,5,6,7,8,9,10,11 ] }
]
});
You can access row data using full variable, for example full[0] or full[1].
However instead of generating links in HTML, I would retrieve row data in a click handler as shown below:
$('#example').DataTable({
"columnDefs": [
{
"targets": [0, 1],
"render": function ( data, type, full, meta ) {
return 'Edit';
}
}
],
// ... other options ...
});
$('#example').on('click', '.btn-edit', function(){
// Get row data
var data = $('#example').DataTable().row($(this).closest('tr')).data();
edit(data[0], data[1]);
});
I needed Edit link on first column, so I followed #Gyrocode.com answer and it works great.
I also wanted to use the global search for searching but only on one column. Datatable ColumnDef Documentation gave me the clue so I ended up doing as follows.
Here The complete code:
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Edit';
}
},
{ targets: 1, searchable: true },
{ targets: '_all', searchable: false }
]
});

jQuery datatable - change cell value

I'm hoping someone can help me with this issue.
I am looking at a legacy application with the older version of datatables.net
It uses the function to populate the datatable and add colour to the row based on a returned name.
The code below works.
$(function () {
$("#ProfileTable").dataTable({
"bProcessing": true,
"bServerSide": true,
"bFilter": false, //Hide the search box
"bInfo": false,
"bPaginate": false,
"bLengthChange": false,
"sAjaxSource": 'DataTableHandler.ashx?dataTableId=ProfileTable',
"aoColumns": [ //aoColumns defines the properties of the table columns
{
"mDataProp": "Name",
"fnRender": function (o) {
return SetToolTip(o);
}
},
{
"mDataProp": "DollarValue",
"fnRender": function (o) {
return accounting.formatMoney(dollarValue);
}
,
"bUseRendered": false,
"sClass": "dataTableTextAlignRight"
}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//Highlight the row colors based on the Name. It must be identical to what is being retrieved from the database
var columnData = aData["Name"];
var div = document.createElement("div");
div.innerHTML = columnData;
if (div.innerText == "TOYS" {
$('td', nRow).css('background-color', '#E0E0E0');
}
if (div.innerText == "LOST TOYS" ) {
$('td', nRow).css('background-color', '#BDBDBD');
}
}
}
What i'm having trouble with is: If the Name = "LOST TOYS" and the DollarValue = 0 then change the DollarValue to display as an empty string (i.e. no value displayed in the cell).
I have looked at using fnUpdate but i can't get it to read the correct row and column. It comes back with "undefined".
Any suggestions are greatly appreciated.
thanks!
I had a brain fart.
The code goes to server side to get the data.
Here's the link to the information:Datatables forum posting about server side source

Using jQuery, how to check whether a table cell is empty or not?

Using jQuery, how to check whether a table cell is empty or not?
Please help me.
What do you mean by empty.
//cell maycontain new lines,spaces,&npsp;,... but no real text or other element
$("cellselector").text().trim()=="";
or
//cell has no child elements at all not even text e.g. <td></td>
$("cellselector:empty")
You can use CSS selectors with the $ function to get a reference to the cell's element, and then use the html function to see whether it has any contents. For instance, if the cell has an ID "foo":
if ($("#foo").html()) {
// The cell has stuff in it
}
else {
// The cell is empty
}
Try this:
$content = $('#your_cell_id_here').html();
if($content == '')
{
// yes it is empty
}
else
{
// no it is not empty
}
You can use the trechnique I posted here
http://www.keithrull.com/2010/06/09/HowToChangeTableCellColorDependingOnItsValueUsingJQuery.aspx
You can use this if you already know the id of the cell you want to check
$valueOfCell = $('#yourcellid').html();
or you can iterate on the cells of the table
$("#yourtablename tr:not(:first)").each(function() {
//get the value of the table cell located
//in the third column of the current row
var valueOfCell = $(this).find("td:nth-child(3)").html();
//check if its greater than zero
if (valueOfCell == ''){
//place action here
}
else{
//place action here
}
});
You could add css classes to your table and its rows and columns, then use jquery selectors to get the table item:
if ( !($('#mytable tr.row-i td.column-j').html()) ) { alert("empty"); }
for datatables, you may use the following
var missedClockoutDataTable = $("#missedClockoutsDatatable").DataTable({
"order": [[0, "asc"]],
"serverSide": true,
"processing": true,
responsive: true,
destroy: true,
select: true,
fixedHeader: {
header: true,
headerOffset: $('#fixed').height()
},
buttons: [
{extend: 'copy', className: 'ui button'},
{extend: 'csv', className: 'ui button'},
{extend: 'excel', className: 'ui button'},
{extend: 'pdf', className: 'ui button'},
],
dom:
"<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"ajax": {
"url": "{{url('workplace/dashboard/employees/missed-clockouts')}}",
data: function (d) {
d.gender = $("#gender").val();
d.roles = $("#roles").val();
},
},
"columns": [
{data: 'full_name', name: 'full_name'},
{data: 'clock', name: 'clock'},
{data: 'in', name: 'in'},
{data: 'out', name: 'out'},
{data: 'numberofHours', name: 'numberofHours'},
{data: 'clockoutReason', name: 'clockoutReason'},
{data: 'action', name: 'action'},
],
//when the table has fully loaded, proceed with looping through each row except the first one and then delete the rows if the IN column cell is empty
"initComplete": function(settings, json) {
// if the in type is empty, then hide that row
$("#missedClockoutsDatatable tr:not(:first)").each(function() {
//get the value of the table cell located
//in the third column of the current row
var valueOfCell = $(this).find("td:nth-child(3)").html();
//check if its greater than zero
if (valueOfCell == ''){
console.log(222);
this.remove();
}
});
}
});

Categories