Jquery Datatable not working? - javascript

I have created a query table using data from json.
I am trying to combine two column values in one
but i always get undefined data when i try to combine two columns.
I am not sure what is wrong here.
not sure what is wrong here
$("#submit").click(function(){
var dataTableExample = $('#tbl_jad').DataTable();
$('#tbl_jad').show();
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample =
$('#tbl_jad').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "ID"
},
{
"mData": "Position_x0020_Number",
},
{
"mData": "Title"
}, {
"mData": "Type_x0020_of_x0020_Action"
}, {
"mData": "Series"
}]
,
"columnDefs": [
{
"render": function ( data, type, row ) {
return data +' ('+ row[0]+')';
},
"targets": 1
},
{ "visible": false, "targets": [ 0 ] }
]
});
}
});

return data +' ('+ row["ID"]+')'
where ID is the column heading or column name

Related

Pass two or more Id column in jQuery data tables as parameter?

I am using jQuery data table. I pass one id via <a href="#">. Now, i want to pass two or more id in single cell and <a href="#">.
My Code:
var table = $('table#companyTable').DataTable({
"sAjaxSource": ResultData, // "/GetcompanyList.json",
"sAjaxDataProp": "",
/// sort at column three
"order": [[ 3, "asc" ]],
"aoColumns": [
{ "mData": null },
{ "mData": "registrationType" },
{ "mData": "companyName" },
{ "mData": "emailId" },
{ "mData": "country" },
{ "mData": "district" },
{ "mData": "registrationDate" },
{ "mData": "companyId" },
{ "mData": "tendererId" },
{
"mData": "userId",
"render": function(data, type, row, meta){
if(type === 'display'){
data = 'View';
}
return data;
}
}
],
// define first column , is column zero
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}]
});
Now i need to pass userId, companyId, tendererId in one render and href link.
Just like below
data = 'View';

Send jquery datatable column value to Javascript Function (Asp.Net MVC)

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) {
...
}

Format currencies when dataTable is created

var oTable = $('#table').dataTable({
"bJQueryUI": true,
"aaData": jsonList,
"bPaginate": true,
"aoColumns": [
{
"mDataProp": null,
"sClass": "control center",
"sDefaultContent": '<img src="http://i.imgur.com/SD7Dz.png">'
},
{ "mDataProp": "ente" },
{ "mDataProp": "cup" },
{ "mDataProp": "decreto" },
{ "mDataProp": "data" },
{ "mDataProp": "importoImpegno" }, //this is a currency
{ "mDataProp": "finanziato" }, //this is a currency
{ "mDataProp": "importoPagato" }, //this is a currency
{ "mDataProp": "importoInPagamento" } //this is a currency
],
"aoColumnDefs": [
{ "sClass": "currency", "aTargets": [ 5, 6, 7, 8 ]}
],
"oLanguage": {
"sInfo": "_TOTAL_ entries"
},
"aaSorting": [[1, 'asc']]
});
As you can see, I add .currency class only to the column where is a currency.
I need to format this currencies (3235 to 3.235,00 for example) and I have already the function to do that.
function currencyFormatIT(num) {
if(num != null && num != "") {
num = parseFloat(num);
num = num
.toFixed(2)
.replace(".", ",")
.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
}
else {
num = "";
}
return num;
}
I tried to use this method so:
$("table.myTable > tbody td.currency").each(function(){
$(this).html(currencyFormatIT($(this).html()));
$(this).css("text-align", "right");
});
But, it's work only with the row that appears in the first page of datatable:
From the second page to onwards not:
If I add this code:
$(document).on("click", "td.currency", function(){
alert($(this).html());
});
works for all td of all page!!
1) Why?
2) If I want to call the currencyFormatIT() function like callback function (maybe in the code where I create the dataTable .dataTable({.. how could I do?
You can use the fnDrawCallback function.
var oTable = $('#table').dataTable({
"fnDrawCallback": function (oSettings) {
// Format Currency here
}
}
You can check the documentation for more details about possible callback functions.

Get DataTables cell value to use in html link

I thought to be a simple thing, but!
Using DataTables, I would like to have the first column of the table hidden and use that cell data in an HTML image link in the next column cell.
html link using "User_ID", http://somepage.php?UID=data0
I have looked at fnGetData() and mRender and I just confused now.
MY CODE:
"aoColumns": [
{ "mData": "User_ID",
"bVisible": false, "bSearchable": false, "bSortable": false
},
{ "mData": null,
"bSearchable": false, "bSortable": false,
"sClass": "center",
"sDefaultContent": '<img src="images/look.png" width="16">'
},
I always help myself with this trick:
Don't set bVisible to false cause you will not have the data in the row. It's not rendered at all. Use sClass and set display:none. This way the column is invisible to the user, but it is still there.
Then you can use mRender to show a custom cell template:
"aoColumnDefs": [{
"aTargets": [0],
"sClass": "hiddenID"
}, {
"aTargets": [1],
"bSearchable": false,
"bSortable": false,
"sClass": "center",
"mRender": function(data, type, full) {
return 'Click me';
}
}, {
"aTargets": [2],
}, ]
Now the data is there, sortable and filterable.
Look at this Plunker and style.css to understand the concept behind this hack.
You may have a closer look at mData so you can do a callback function and dont have to use the hidden column:
// Using mData as a function to provide different information for
// sorting, filtering and display.
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"aoColumns": [
{ "mData": "User_ID",
"bVisible": true, "bSearchable": false, "bSortable": false
}
],
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": function ( source, type, val ) {
if (type === 'set') {
source.id = val;
// Store the computed dislay and filter values for efficiency
source.id_display = val=="" ? "" : '<img src="images/look.png" width="16">';
source.id_filter = val=="" ? "" : val;
return;
}
else if (type === 'display') {
return source.id_display;
}
else if (type === 'filter') {
return source.id_filter;
}
// 'sort', 'type' and undefined all just use the integer
return source.id;
}
} ]
} );
} );

Sort datatable by hidden column

I have datatable with id, firstName, lastName, phone, updated fields.
Problem: I add to datatable only four fields (id, firstName, lastName and phone). Updated field is hidden.
Question: how to sort datatable by updated field?
My code:
$('#table').dataTable({
sDom: '<"top"fi>tS',
sScrollY: ($(window).height() - 250) + "px",
bPaginate: false,
bDeferRender: true,
bAutoWidth: false,
oLanguage: {
sInfo: "Total: _TOTAL_ entities",
sEmptyTable: "No pending entities"
},
"aoColumnDefs": [
{ "iDataSort": 4, "aTargets": [ 0 ] }
],
"aoColumns": [
{ "sWidth": "10%" },
{ "sWidth": "40%" },
{ "sWidth": "30%" },
{ "sWidth": "20%" },
{ "sTitle": "updated ", "bVisible":false }
],
fnCreatedRow: function( nRow, aData, iDataIndex ) {
$(nRow).attr('id', aData[0]);
}
});
table.fnAddData([id, firstName, lastName, phone, updated]);
From the documentation:.
iDataSort The column index (starting from 0!) that you wish a sort to be performed upon when this column is selected for sorting. This can be used for sorting on hidden columns for example.
Default: -1 Use automatically calculated column index
Type: int
// Using aoColumnDefs
$(document).ready( function() {
$('#example').dataTable( {
"aoColumnDefs": [
{ "iDataSort": 1, "aTargets": [ 0 ] }
]
} );
} );
// Using aoColumns
$(document).ready( function() {
$('#example').dataTable( {
"aoColumns": [
{ "iDataSort": 1 },
null,
null,
null,
null
]
} );
} );
you can simply use { "iDataSort": 4 } here (4 is the index of your hidden field)
var data = [
["1","john","mathew","1234",[]],
["2","Mary","rose","1234","1"],
];
To add hidden fields and to add data to table
aaData: data,
aoColumns :[
{ "sTitle": "id","bSortable": false },
{ "sTitle": "firstName","bSortable": false, },
{ "sTitle": "lastName", "bSortable": false,},
{"sTitle": "phone","bSortable": false},
{"sTitle": "updated ", "bVisible":false },
]
To add hidden fields use "bVisible":false
I was facing a problem by sorting the hidden column in runtime, don't know the approach is valid or not. I used the following lines to hide the column via CSS
td:nth-of-type(2) {
display: none;
}
Where 2 is your column, assign a class to your <th class="mycolum1"> and use jquery to sort it like
$("#button").click(function(){
$(".mycolumn").click();
})
Pardon me if the approach is not valid but in my case it is 100% acceptable.

Categories