I'm using Datatables and I'm trying to access data in another column. It's unclear to me if I should be using columns.data or if I should be taking another approach by using getting the column index instead?
Objective
In the second render function, I want the first makeSlug(data) to be referencing the "data": "district" and the second one to remain the same and reference "data": "school"
scripts.js
"columns": [
{ "data": "district",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
{ "data": "school",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
{ "data": "subject"},
{ "data": "rate"},
{ "data": "test_takers"}
],
Third argument row is an array containing full data set for the row. Use row['district'] to access district property.
For example:
{
"data": "school",
"render": function (data, type, row, meta) {
return '' + data + '';
}
}
Related
I'm new to datatable ajax serverside data fething uisng php jquery ajax. I have to fetch data but now I want to add a dropdown in some columns to submit the data for a particular row.
In my table column with the name of "QA Status", I want to add a dropdown to every row.
and the dropdown option is 1) Pending 2) Accepted 3) Rejected
See the image
I want to add dropdown using jquery datatable using columns
This is my code for showing the data in the table
"columns": [
{
"render": function(data, type, full, meta) {
return "";
}
},
{ "data": "created_at" },
{ "data": "campaign" },
{ data: null, render: function ( data, type, row ) {
return data.fname+' '+data.lname;
}
},
{ "data": "c_name" },
{ "data": "qa_status" },
{ "data": "qa_resone" },
{ "data": "client_status" },
{ "data": "client_resone" },
{ "data": "score" }
]
In this code { "data": "qa_status" } I want to show a dropdown and I want also to add submit button in the last column of every row for selected value submitted without page reloading.
please help me.
try adding following and see if that works:
put following code inside datatable option:
let data_table = $(".table_class").DataTables({
columns: [
...
],
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var select = $('<select style="width:100%;"><option value="">Select</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.draw(false).data().unique().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
});
I am trying to get the <span> tag into the "salesStatusName" column cell that already has some data in it. The tag should be placed in there when the value of the last column "completelyDelivered" is true. However, I also don't want "completelyDelivered" to even be a column in the table, so I assume I somehow need to access the value of "completelyDelivered" attribute in the received JSON.
How it looks now:
https://i.imgur.com/S171i2o.png circle in a separate column
How I want it to look:
https://i.imgur.com/74nCnGu.png circle within Status Name column
I looked around and there are very similar questions, but I was unable to implement any solution.
DataTables instantiation code:
Note that I use AJAX and get JSON code returned
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
"columns": [
{ "data": "salesOrderNumber" },
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": "salesStatusName" },
{ "data": "completelyDelivered" }
],
"columnDefs": [
{
"targets": 0, //salesOrderNumber col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/Get?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 7, //completelyDelivered col
"render": function (data) {
if (String(data) == "true") {
return '<span class="SalesOrderDelivered">⬤</span>';
}
return "";
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});
I've done some research and figured it out.
Basically, if you write { "data": null }, as a definition for a column, you gain access to all properties of that row. So, in "render": function(data) function, write data["propertyName"] to get the value.
Code:
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
{"data": "salesOrderNumber",},
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": null, },//this is Sales Status column.
//"data: null" accesses all JSON data. We need this so that in "columnDefs" section
//we can use the values of both "completelyDelivered" and "salesStatusName" properties.
],
"columnDefs": [
{
"targets": 0, //button col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/GetShipments?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 6, //Sales Status col.
"render": function (data) { //This is where we can use values of "completelyDelivered" and "salesStatusName" JSON properties.
if (String(data["completelyDelivered"]) == "true") {
return (String(data["salesStatusName"]) + '<span class="AllDelivered"> ⬤</span>');
} else {
return String(data["salesStatusName"]);
}
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});
I am binding data to jquery datatable in asp.net mvc, i have an anchor tag in one of the columns of the grid where i am accessing / reading row data and sending that data to a javascript function. The problem which i am facing is, i am able read and send row values to the function which are numbers for example ProductID="1" or CategoryID="3" , but if i try to send ProductName="Chai" to the javscript function i get an error in the console, and if i remove the parameter "ProductName" everything works fine and the javascript function also gets triggered.
Following the console error:
"Index:1 Uncaught ReferenceError: Chai is not defined
at HTMLAnchorElement.onclick (Index:1)"
Following is my Code:
var BindDataTable = function (response) {
$("#tbProduct").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "ProductID" },
{ "mData": "ProductName" },
{ "mData": "SupplierID" },
{ "mData": "SupplierName" },
{ "mData": "SupplierCountry" },
{ "mData": "CategoryID" },
{ "mData": "CategoryName" },
{ "mData": "QuantityPerUnit" },
{ "mData": "UnitPrice" },
{
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
}
],
"columnDefs": [
{
"targets": [2],
"visible": false,
"searchable": false
},
{
"targets": [5],
"visible": false,
"searchable": false
}
],
"aaSorting": []
});
}
var EditProduct = function (ProductID, SuppID, CatID,PrdName) {
var url = "/Product/EditProduct?ProductID=" + ProductID + "&SuppID=" + SuppID + "&CatID=" + CatID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
Error:
My suggestion is that instead of playing around with that much string concatenations, what you can do is pass single object to your function and then use the required fields which needs to be passed as ajax call:
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
and in your js function use it :
var EditProduct = function (product) {
var url = "/Product/EditProduct?ProductID=" + product.ProductID+ "&SuppID=" + product.SupplierID + "&CatID=" + productCategoryID + "&ProdName=" + product.Prooductname ;
You can use the following approach in for passing string arguments to a JavaScript function:
<a onclick="javaScriptFunction(#p.ID, '#p.FileName');">#p.FileName</a>
function javaScriptFunction(id, fileName) {
...
}
So when I'm creating a DataTable in react, defining a certain column using the columnDefs property.
"columnDefs": [
{
"targets": 7,
"data": "data",
"render": function ( data, type, full, meta ) {
return "<button onclick='test()'>view</button>"
}
}
]
But as expected, it can't find the test() function. Is there anyway to do this jsx style or something? Or will I just have to create the function inside the onclick?
You can try like this:
$('#your_table').DataTable({
. . .
"columnDefs": [{
"targets": 7,
"data": "data",
"render": function ( data, type, full, meta ) {
return "<button class='view_btn' data-id='"+data+"'>view</button>"
}
}]
Then create the test function outside:
$('#your_table').on('click', '.view_btn', function(){
var id = $(this).data('id');
test(id); // your function
});
You can't use render in this case as the function will be called directly. You can use arrow function and createdCell insetead in columnDefs.
For example you have a function in a component:
this.test= this.test.bind(this);
Call that function in columnDefs by:
"columnDefs": [{
"targets": 0,
"data": "data",
"createdCell": (td, cellData, rowData, row, col) => {
$(td).click(e => {
this.test();
})
}
}]
Take a look at the link above for more information.
You can use the arrow function and this object
"columnDefs": [
{
"targets": 7,
"data": "data",
"render": ( data, type, full, meta ) => {
return "<button onclick='this.test()'>view</button>"
}
}
]
I have a table that I have successfully created with Datatables. I am trying to show data with a hyperlink. When I use columnDefs, the columns performs as expected and shows a bit of data (as expected) with a hyperlink. Here is the code:
// below works as expected. It shows the ID which is the data
// in a hyperlink
"columnDefs": [{
"targets": 0,
"data": "download_link",
"render": function(data, type, full, meta) {
return '' + data + '';
}
}]
On the otherhand, I am trying to do the same thing using "columns" and it does not produce a similar result. The below example shows "undefined" but it does produce a hyperlink to undefined. Here is the code snipplet:
"ajax": "json_get_countries",
// country column does not work as expected. It shows "undefined" and a hyperlink
// connected to the word underdefined
"columns": [{
"data": "country_id",
"searchable": false
},
{
"data": "country",
"data": "download_link",
"render": function(data, type, full, meta) {
return '' + data + '';
}
},
{
"data": "country_enabled"
}
]
I have tried to remove this code:
"render": function(data, type, full, meta) {
return '' + data + '';
and it does work. It does show the data just without the hyperlink.
I have tried to change +data+ to +country+ but that also did not work.
Any help appreciated.