How to assign an ID to a button in DataTables? - javascript

I have a table with some content and Edit button. This is the code which produces a datatable:
$(document).ready(function() {
var params = {};
callFunction("getAgentList", params,
function(bSuccess, res) {
var table = $('#example').DataTable({
data: res,
"columns": [
{ "data": "ID" },
{ "data": "Name" },
{ "data": "AltName1" },
{ "data": "AltName2" },
{ "data": "AltName3" },
{ "data": "AltName4" },
{ "data": "AltName5" },
{ "data": "AltName6" },
{ "data": "AltName7" },
{ "data": "AltName8" },
{ "data": "AltName9" },
{ "data": "AltName10" },
{
"orderable": false,
"data": null,
"defaultContent": '<button class="btn btn-warning" id='+res+' onclick="edit(this)">Edit</button>'
},
],
"order": [
[1, 'asc']
]
});
}
);
});
Each row should have an edit button for editing that specified row. For this I need an ID which I have in res JSON. But I am not sure how to get the ID for each of the edit buttons?
Right now if I put only res I get Object or with res.ID it is undefined. Which makes sense because I need to loop over the array...
Anyone?
EDIT
This is the res JSON:
{ AltName1: "Test1", AltName10: "", AltName2: "Test1Alt", AltName3: "Test1", AltName4: "Test1", ID: "1" }
{ AltName1: "Test2", AltName10: "", AltName2: "", AltName3: "", AltName4: "", ID: "2" }
If I set the id as <button class="btn btn-warning" id='+res[0].ID+' onclick="edit(this)">Edit</button>
Then all buttons have the same ID.

Change all the first letters to lowercase in JavaScript then use the render function of datatable:
{ "targets": 0, "data": 'iD' },
{ "targets": 1, "data": 'name' },
{ "targets": 2, "data": 'altName1' },
{ "targets": 3, "data": 'altName2' },
{ "targets": 4, "data": 'altName3' },
{ "targets": 5, "data": 'altName4' },
{ .... },
{
"targets": 6,
"data": 'iD',
"render": function (data, type, row, meta) {
return '<button class="btn btn-warning" id='+data+' onclick="edit(this)">Edit</button>'
}
}
In the render function you can access the ID with different ways :
1 : "data" : 'iD' then you use data (as I did)
2 : "data" : 'anything you want' then you use : row.iD
Also note please that you need to add a prefix before the ID to avoid repeated Id's (I always do that)

just try this
"defaultContent": '<button class="btn btn-warning" id='+ID+' onclick="edit('+ID+')">Edit</button>'

Related

Format data returned from JSON in DataTable [duplicate]

This question already has answers here:
use of comma and datatable decimals
(2 answers)
Closed 7 months ago.
I am reading a json file from remote url and displaying it in DataTable.
<script>
$(document).ready(function () {
$('#example').DataTable(
{
ajax: {
method: 'GET',
url: 'https://chainformed.s3.us-east-1.amazonaws.com/Data/mostwatched.json',
dataSrc: ''
},
paging: false,
responsive: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.12.1/i18n/tr.json",
},
columns: [
{ "data": "id" },
{ "data": "rank" },
{ "data": "name" },
{ "data": "watchlist" },
{ "data": "percentage" },
{ "data": "difference" },
{ "data": "timestamp" }
]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
I would like to be able to format and manipulate the data returned from that json file. What is the best way to do it?
For example, i would like to change the values from ({ "data": "watchlist" }) field to number format with comma. How can i achieve it?
I tried this but with no luck: https://datatables.net/reference/option/ajax.dataSrc
Use render element.
Read document from Format output data - orthogonal data
and example
Another way u can use columnDefs
<script>
$(document).ready(function () {
$('#example').DataTable(
{
ajax: {
method: 'GET',
url: 'https://chainformed.s3.us-east-1.amazonaws.com/Data/mostwatched.json',
dataSrc: ''
},
paging: false,
responsive: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.12.1/i18n/tr.json",
},
columns: [
{ "data": "id" },
{ "data": "rank" },
{ "data": "name" },
{ "data": "watchlist" },
{ "data": "percentage" },
{ "data": "difference" },
{ "data": "timestamp" }
],
'columnDefs': [
{
"targets": 3,
"data": "watchlist",
"render": function ( data, type, row, meta ) {
return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
]
});
$('.dataTables_length').addClass('bs-select');
});

How to reduce repetition in Javascript code?

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

Ordering columns in JQuery DataTable -- when data is fed through Javascript

There are some forum questions similar to what I'm trying to do but I haven't been able to make it work.
We are pulling data into a DataTable through javascript. I'd like to set the data-order using a different column.
However, when I try the column is being interpreted as a string and not integer.
Here is what makes the table:
var securityTable = $('#security-table').DataTable({
"data": securitydata.guards,
"columns": [
{
"className": 'details-control',
"data": null,
"orderable": false,
//creates square for details row
"render": function (d) {
return '<i class="fa fa-plus-square" aria-hidden="true"></span>';
},
"defaultContent": ''
},
// is sorting by "sort" but is seeing numbers as alphebetical not numeric
{ "data": {
_: "date.display",
sort: "date.date_order"
} },
{ "data": "place" },
{ "data": {
_: "shot.display",
sort: "shot.shot_order"
} },
],
"paging": false,
"searching": false
});
This is what the data looks like:
var securitydata = {
"guards": [
{
"date": {
"display": "April 15, 2011",
"date_order": 1
},
"reported": "Yes",
"place": "Chicago, auto parts yard",
"shot": {
"display": "No one hit",
"shot_order": 24
},
"blurb": "A 52-year-old guard at an auto parts lot shot at a vehicle he said was coming toward him. The man inside the vehicle, accused of stealing equipment from the lot, drove away and was not reported injured.",
"link": ""
},
This is what we were using for help
Using the same example, but with sorthing
$(document).ready(function() {
$('#example').DataTable( {
order: [[ 2, "desc" ]],
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp"
} },
{ data: "salary" }
]
} );
} );
Link to order here

jquery datatable doesn't sort

I have a jquery datatable that is populated by server side ajax. Supposedly, datatables are supposed to be sortable by default without having to add any parameters. Mine isn't. The sort arrows show up in the column headers and clicking on them flips the arrow but nothing gets sorted.
Here's the datatable definition:
$('#appPotTable').DataTable({
"ordering": true,
"processing": true,
"serverSide": true,
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol", "sortable":true },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});
I've tried it with and without the "ordering" and "sortable" parameters but same result. I've also tried various column definition parameters with no joy. Suggestions?
Thanks to Ogreucha for suggesting to turn off server side processing. I did that and now sorting works fine. Here is the new code:
$('#appPotTable').DataTable({
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});

How to Pass geojson array to datatable dyanamically using javascript

I want to pass one geojson file to dynamically created datatable using javascript,I am unable to identify column names in file..
I have tried this..
CODE
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>fC.type</th>
<th>f.type</th>
<th>f.prop</th>
<th>f.geom.type</th>
<th>geometry.coordinates.0</th>
<th>geometry.coordinates.1</th>
</tr>
</thead>
</table>
</body>
$(document).ready(function () {
$('#example').dataTable({
"ajax": "data/json_file.json",
"processing": true,
"columns": [
{ "mData": "type" },
{ "mData": "features.type" },
{ "mData": "features.properties" },
{ "mData": "geometry.type" },
{ "mData": "geometry.coordinates.0" },
{ "mData": "geometry.coordinates.1" }
]
});
});
geojson File
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[
40.078125,
57.136239319177434
],
[
91.7578125,
58.99531118795094
]
]
}
}
]
}
My output is as shown in image
The problem is actually the datafile, which is valid JSON but not the structure that datatable requires.
Solution 1 : Change the file to expected structure.
{
"data": [
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[
40.078125,
57.136239319177434
],
[
91.7578125,
58.99531118795094
]
]
}
}
]
}
]
}
Solution 2 : Use the dataSrc through which you can modify the ajax response before datatable uses it.
$('#example').dataTable({
"ajax":
{
"url": "json1.json",
"dataSrc": function (json) {
var obj = [];
obj.data = [];
obj.data[0] = json;
return obj.data;
},
},
"processing": "true",
"columns": [
{ "data": "type" },
{ "data": "features.0.type" },
{ "data": "features.0.properties" },
{ "data": "features.0.geometry.type" },
{ "data": "features.0.geometry.coordinates.0" },
{ "data": "features.0.geometry.coordinates.1" }
]
});
Here what I've done is created a new object obj.
Working fiddle here : https://jsfiddle.net/ourqh9ts/
The problem might be that the GeoJSON is not an array but an object.
Try changing your column definitions with these:
"columns": [
{ "data": "type" },
{ "data": "features.0.type" },
{ "data": "features.0.properties" },
{ "data": "features.0.geometry.type" },
{ "data": "features.0.geometry.coordinates.0" },
{ "data": "features.0.geometry.coordinates.1" }
]

Categories