Javascript Datatables generating HTML link using render function on JSON data - javascript

I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );

Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/

Related

How can I do any multiplication or any mathematical operation for 2 rows in data table

I am new to development, and trying to build data table with JSON. So far I did
{
"qty": "2",
"price": 1
}, {
"qty": "3",
"price": "5",
}, {
"qty": "3",
"price": "4",
}
var table = $('#example').DataTable({
data: dataSet,
columns: [{
title: "qty",
data: "qty"
},
{
title: "price",
data: "price",
render: function(data, type, row) {
return '<input type="number" value="' + data + '">';
},
{
title: "total",
data: "multiplication'}
}
]
I want to perform multiplication of two rows qty and price and store result in third row.
Consider another example.
$(function() {
var dataSet = [{
"qty": 2,
"price": 1.00,
},
{
"qty": 3,
"price": 5.99
},
{
"qty": 3,
"price": 4.00
}
];
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
$.each(dataSet, function(i, r) {
r.total = calcTotal(r.qty, r.price);
});
var table = $('#example').DataTable({
data: dataSet,
columns: [{
"data": "qty"
},
{
"data": "price",
"render": function(data, type, row) {
return '$<input type="number" class="price-input" min="0.00" step="0.01" value="' + data + '" />';
}
},
{
"data": "total",
"render": function(data, type, row) {
return "$" + data;
}
}
]
});
$("#example").on("change", ".price-input", function(event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(0)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(2).get(0));
total.data(calcTotal(qty, price)).draw();
});
});
td {
text-align: center !important;
}
.price-input {
width: 5em;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This updates the Data Set before building the Table. So the values are already there. You can then use a change callback to modify that data.
Note: Most interfaces want to change the Quantity and not the price, but since your example changed the Price, I kept it as is. You can easily modify this to work the other way.
Here is a simple solution you can do this with columnDefs option:
In your column definition, add a third data column with the value null. (Remember to have the number of columns matching in your HTML). I created a third HTML column with the <th>Total</th>. The table will render the column empty.
When it gets to the columnDef, you want to make sure you target the correct column, remember it reads them based on a 0 index, so 2 is actually 3.
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return type === 'display' ? ((full.qty)*(full.price)) + '' : data;
}
Remember, the full parameter is the data for the entire row, so in the return of your render, you multiply the two data values (full.qty)*(full.price)
var dataSet = [
{
"qty": "2",
"price": "1",
},
{
"qty": "3",
"price": "5"
},
{
"qty": "3",
"price": "4"
}]
var table = $('#example').DataTable({
data: dataSet,
columns: [
{"data" : "qty"},
{"data": "price"},
{"data" : null}
],
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return "$" + ((full.qty)*(full.price));
}
}]
});
td {
text-align: center !important;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How to get value from each datatable row dropdownlist

I'm working with Datatable. The problem is I need to get all the values from each row's dropdownlist. The datatable have the column 'Company' which the user need to select value from dropdownlist .Now I'm able to get each row's value for Citizen_ID and Tel using the code below.
var rowData = table.rows().data();
var dataArr = [];
$.each($(rowData), function(key,value){ //data
let tempObj = {
Citizen_id: value["Citizen_ID"],
Tel: value["Tel"]
}
dataArr.push(tempObj);
});
How can I get selected value from dropdownlist for all datatable pages?.
I would approach this in a slightly different way.
Some of the data you need can be accessed from the DataTable, but the selected value in each row's drop-down list only exists in the DOM, so you need the related DOM node to access that data.
I would therefore populate the following two variables, at the start:
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
Both of these are populated using DataTables API calls, so the entire table is processed.
This gives you two arrays - one with the DataTables data objects for each row, and the other with the DOM nodes.
Then you can use a traditional for loop to iterate the arrays in parallel, and extract the specific pieces of data you need.
For the drop-down node, you can use a jQuery selector:
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
I used a class (value = company) in the HTML code for the select, just in case there are multiple different selects in one row.
Here is a demo of the overall approach:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
</table>
<br>
<button id="data_btn" type="button">Get Data</button>
</div>
<script>
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
];
$(document).ready(function() {
var table = $('#example').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Company",
defaultContent: '',
render: function ( data, type, row, meta ) {
if (type === 'display') {
return '<select class="company">'
+ '<option value="Google">Google</option>'
+ '<option value="Microsoft">Microsoft</option>'
+ '<option value="Amazon">Amazon</option></select>';
} else {
return data;
}
}
},
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
]
} );
$("#data_btn").on( "click", function() {
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
var dataArr = [];
for (i = 0; i < rowData.length; i++) {
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
let tempObj = {
id: rowData[i].id,
name: rowData[i].name,
company: selectedCompany
}
dataArr.push(tempObj);
}
console.log( dataArr );
});
} );
</script>
</body>
</html>
When you run the demo, first select a "company" value in each of the drop-downs.
Then click the "Get Data" button.
The resulting object will look similar to the following:
[
{
"id": "123",
"name": "Tiger Nixon",
"company": "Amazon"
},
{
"id": "456",
"name": "Donna Snider",
"company": "Microsoft"
}
]

How to create child row to display the order details in jquery datatable?

I have one service that returning the list of data. I want to show the ordered item details each order wise in jquery datatable.
Could anyone help me with this?
Inside JSP
<table class="table table-bordered" id="physicalOrderDataTable">
<thead>
<tr>
<th>#</th>
<th>PRODUCT</th>
<th>VARIANT</th>
<th>ADDRESS</th>
<th>STATUS</th>
<th>PACKING ID</th>
<th>TRACKING ID</th>
<th>ACTION</th>
</tr>
</thead>
</table>
</div>
Here is the js file for this
Inside Js File
$('#physicalOrderDataTable').DataTable({
destroy: true,
"serverSide" : true,
lengthChange : false,
ordering : false,
paging : true,
"pagingType" : "full_numbers",
processing : true,
autoWidth : true,
oLanguage : {
sSearch : 'Search:'
},
ajax : {
url : 'service/getAllOrderDetails',
dataSrc : 'details',
"type" : "GET"
},
columns : [{
"render": function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},{
data : 'orderNo'
}, {
data : 'VariantName'
}, {
data : 'address'
} , {
data : 'status'
}, {
data : 'packingId'
}, {
data : 'trackingId'
}, {
'data': 'orderDetailsId',
"render": function (orderDetailsId, type, full, meta) {
// debugger
return '<button class="btn btn-info btn-sm addBank" data-uId="'+orderDetailsId+'" data-toggle="tooltip" data-placement="top" title="Update" ><i class="fa fa-university"></i></button>';
}
}
],
"fnDrawCallback": function() {
//Initialize tooltip
$('[data-toggle="tooltip"]').tooltip();
},
columnDefs: [
{ width: '2%', targets: 0 }
]
});
here is the json structure of rest service.
My Json
"details": [
{
"orderNo": "OD-181120192",
"onlineCartPhysicalOrderDetails": [
{
"orderDetailsId": 9,
"productName": "Casual Shirt",
"address": "dffdf",
"status": "PENDING",
"packingId": null,
"trackingId": null,
"variantName": "Puma Casual Shirt"
},
{
"orderDetailsId": 10,
"productName": "Casual Shirt",
"address": "XYZ",
"status": "PENDING",
"packingId": null,
"trackingId": null,
"variantName": "Red Medium Casual Shirt"
}
]
},
{
"orderNo": "OD-181120191",
"onlineCartPhysicalOrderDetails": [
{
"orderDetailsId": 8,
"productName": "Casual Shirt",
"address": "ERTTY",
"status": "PENDING",
"packingId": null,
"trackingId": null,
"variantName": "Puma Casual Shirt"
}
]
}
],
"draw": 1,
"length": 10,
"recordsTotal": 2,
"recordsFiltered": 2
}
I want to show the order details like this in datatable. could any one please help me on this ?
Use DataTables and RowGroup functionality for this
Reference link rowgroup example link

Datatable - DOM sourced Object array will not load data

I'm trying to initialise a datatable using an object array located in the DOM
I have simple datatable initialisation code:
$(document).ready(function () {
$('#ManageSubReps').DataTable({
data: GetSRData(),
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
});
});
My GetSRData function looks like this:
function GetSRData() {
return #Html.Raw(Model.JsonData)
}
My server side code looks like this:
public ActionResult ManagerSubReps(){
var model = new ManageSubRepsViewModel();
model.JsonData = JsonConvert.SerializeObject(new {data = _iManageSubRepsManager.GetSubRepsAsync(Session["CID"])});
return View(model);
}
A snipped of my data looks like this:
{"data":[{"username":"01001MC","MASTER":null,"Name":"A name","Address":"105 Address Dr.","City":"Agawam","State":"MA","Zip":"89898","EmailAddress":"blerb#yahoo.com","HomePhone":"","CellPhone":"8767878767","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null},{"username":"01002RG","MASTER":"False","Name":"Blooby palooby","Address":"7 Eaton drive, gumbie#Gmail.Com","City":"Amherst","State":"MA","Zip":"35656","EmailAddress":"chumpy#GMAIL.COM","HomePhone":"","CellPhone":"8986786654","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null}]}
HTML:
<table id="ManageSubReps" class="compact display">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th class="dt-left">Name</th>
<th class="dt-left">Address</th>
<th class="dt-left">City</th>
<th>State</th>
<th>Zip</th>
<th class="dt-left">Email</th>
<th>Home Phone</th>
<th>Cell Phone</th>
<th>New Rep</th>
<th>Stand By</th>
<th>Approved Date</th>
<th></th>
</tr>
</thead>
</table>
When I return my data and try to initiliase the datatable, two things can happen:
If I remove the "data" part of the Json object then datatales will render the datatables but will not have any data in
If I leave the "data" part of the Json object then datatables will give me the error: 'Request unknown parameter '0' for row 0, column 0'. Which basically means that it cannot distinguish the data and form the datatable with the data.
I have checked the column data and it matches perfectly fine. I cannot figure out what the issue is.
Can anyone help?
EDIT: I know the issue has something to do with the data being a string, as I call HTML.Raw() on it. However, Im unsure of how to pass the data from the model without this
try ajax instead of data & fully qualified url(controller/api method) for getting ajax data:
$(document).ready(function() {
$('#ManageSubReps').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "ManagerSubReps",
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
} );
} );
refer https://datatables.net/examples/server_side/object_data.html for more details.

DataTables Javascript data source 'No Data Available'

Live error example: http://live.datatables.net/virobeci/1/edit?html,css,js,output
I have a JavaScript object similar to this:
{
"rows": [
{
"doc": {
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
},
{
"doc": {
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
}
]
}
I've been trying for a long time to get DataTables to initialize using JavaScript datasource as mentioned here:
https://datatables.net/examples/data_sources/js_array.html
This is what I'm doing:
var table = $('#customersTable').DataTable( {
data: view,
columns: [
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' }
]
});
I get no errors, just 'No data available in table'
Table is defined like this:
<table id="customersTable" class="table table-striped table-bordered" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Login</th>
<th>Party</th>
<th>Sales-Id</th>
<th>Sales-Party</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Number</th>
<th>Login</th>
<th>Party</th>
<th>Sales-Id</th>
<th>Sales-Party</th>
</tr>
</tfoot>
</table>
Live example: http://live.datatables.net/virobeci/1/edit?html,css,js,output
Edit -> PLEASE NOTE:
I can't change the format of the data source other than running a for loop and making a new array to match the sample data source. I wanna know if its possible to initialize the table with this type of data source
You haven't form your data properly:
var view = {
"rows": [
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
},
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
},
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
]
};
And you have to assign the right array as data.row (although in your case you could simplify your structure a bit removing one level).
Note that you will have to add the data to the 'data' property of 'columns':
var table = $('#customersTable').DataTable( {
processing: true,
data: view.rows,
columns : [
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' }
]
});
you have to mention column name in your "columns" config and your data can be flattened.
http://live.datatables.net/poganaso/2/edit
you can try this,sample code is here:http://live.datatables.net/virobeci/2/edit?html,css,js,output

Categories

Resources