create empty rows in the data tables - javascript

i want to create a table in the datatables which does not have data in the last rows data. i wanna leave it empty with borders. right now i when i 10 rows of data 4on each page. the data get into 3pages where first and second page have 4 rows and when we reach the third page there is only two data and the other space is left blank. i wanna create a table and then fetch data but the datatable is creating the table in my code so. cud anyone suggest how can i leave the last two rows blank and visible.
var dataSet = [];
for(var i = 0; i < data.response.docs.length; i++)
{
var d = data.response.docs[i];
var minPrice = d.min_price;
var minPrice = d.shipping;
var seller_rating = d.rating;
var product_rating = d.product_rating;
var total = minPrice + shipping;
var ships_on = 'n/a';
var delivered_by = 'n/a';
dataSet.push([{ 'url': d.url},
total,
minPrice + '+' + shipping,
ships_on, delivered_by,
seller_rating, product_rating]);
}
$('#data_table').dataTable( {
"aaData": dataSet,
"aaSorting": [[0,'asc'],[0,'desc'],[2,'asc'],[2,'desc'],[3,'asc'],[3,'desc'],[4,'asc'],[4,'desc'],[5,'asc'],[5,'desc'],[6,'asc'],[6,'desc'],[7,'asc'],[7,'desc']],
"iDisplayLength": 4,
"bInfo": true,
"bLengthChange": false,
"bJQueryUI": true,
"bPaginate": true,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"aoColumns": [
{ "sTitle": "Seller",
"sWidth": "155px",
"sClass": "grey" ,
"fnRender": function(obj) {
var data = obj.aData[ obj.iDataColumn ];
return "<A href='"+ data.url +"'>"+ data.title +"</A>";
}
},//, "sWidth": "130px"
{"sTitle": "Item Matched","sWidth": "100px","sClass":"center yellow","bSortable": false,
"fnRender": function (obj) {
//var img = obj.aData[obj.iDataColumn];
var data = obj.aData[obj.iDataColumn];
return "<img width='90px' height='50px' src='" + data.image + "'/><br>"+ data.name.slice(0,25);
}
},
{ "sTitle": "Total Price(in $)","sClass": "center grey" },
{ "sTitle": "Price + Shipping(in $)","sClass": "center yellow" },
{ "sTitle": "Ships On", "sClass": "center grey" },
{ "sTitle": "Delivered By","sClass": "center yellow" },
{
"sTitle": "Seller rating",
"sClass": "center grey",
"fnRender": function(obj) {
var sReturn = obj.aData[ obj.iDataColumn ];
var val = obj.aData[ obj.iDataColumn ];
if ( sReturn != "N/A") {
$('#fixed').raty({
readOnly: true,
start: val
});
sReturn = $('#fixed').html();
$('#fixed').html("");
}
return sReturn;
}
},
});
I just want the last two rows to be visible wheater they have data or not
if(dataSet != '' || no/4 != 0)
{
//alert(no);
var minPrice = 0;
var shipping = 0;
var seller_rating = 0;
var product_rating = 0;
var ships_on = 'n/a';
var delivered_by = 'n/a';
var total = minPrice + shipping;
var a = no%4;
for(var i=0;i<(4-a);i++)
{
dataSet.push([{'title': '', 'url': ''},
{'image': '', 'name': ''},
'0',
'0',
'n/a', 'n/a',
'0', '0']);
}
}
$('#data_table').dataTable( {
"aaData": dataSet ,
"bSort":true,
"aaSorting": [[0,'desc'],[0,'asc'],[2,'asc'],[2,'desc'],[3,'asc'],[3,'desc'],[4,'asc'],[4,'desc'],[5,'asc'],[5,'desc'],[6,'asc'],[6,'desc'],[7,'asc'],[7,'desc']],
"iDisplayLength": 4,
"bInfo": true,
"bLengthChange": false,
"bJQueryUI": true,
"bPaginate": true,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"aoColumns": [
{ "sTitle": "Seller",
"sWidth": "155px",
"sClass": "grey" ,
"fnRender": function(obj) {
var data = obj.aData[ obj.iDataColumn ];
return "<a href='"+ data.url +"'>"+ data.title +"</a>";
}
}
Its creating two rows which is not having data and is empty. and will create two empty row. I needed data where in each page thereare 4 data in each page. so i m using it in mutiples of 4.

I don't know about the datatable plugin you have been using however you can pad your dataset with empty values to make it work:
var dataset = ['1','2','3','4','5','6','7','8','9'];
var rowCount = 4;
var mod = dataset.length%rowCount;
if(mod) {
for(var i=mod; i<rowCount;i++) {
dataset.push('')
}
}
http://jsfiddle.net/bsrykt/JJtNN/

Related

Uncaught TypeError: Cannot read property 'style' of undefined using datatable pipeline

I am using Datatable pipeline for generating table. My table has dynamic column means it has no fixed column. The column column number changes with the change of a month. Suppose, during current month the table has 4 column but for november it has 32 columns. When I changes month to november,it gives me Cannot read property 'style' of undefined this error.
My datatable initilization function:
function monthlyAttendanceStatusDatatableInit(tableIdOrCss, url, columns, sortArr, pageLength, year, month) {
console.log(columns);
var param = {
"responsive": false,
// "columnDefs": [
// {responsivePriority: 1, targets: -1},
// {responsivePriority: 2, targets: 0}
// ],
"aLengthMenu": [[10, 20, 50, -1], [10, 20, 50, 'All']],
"pageLength": pageLength || 10,
"iDisplayLength": pageLength || 10,
//"language": { search: "" },
"sPaginationType": "simple_numbers", // you can also give here 'simple','simple_numbers','full','full_numbers'
"oLanguage": {
"sSearch": "Search:",
"sProcessing": "Loading..."
},
"ajax": $.fn.dataTable.pipeline( {
url: url,
data: {
'month': month,
'year': year
},
pages: 2 // number of pages to cache
}),
"processing": true,
"serverSide": true,
"searching": true,
// "bPaginate": true,
// "fnDrawCallback":function(){
// if(typeof callBack == 'function'){
// callBack();
// }
// },
"destroy": true,
"paging": true,
"retrieve": false,
"aoColumns": columns,
"aaSorting": sortArr, //[[ 0, "asc" ],[ 1, "desc" ]] // Sort by first column descending
// "scrollX": true,
// "createdRow": function( row, data, dataIndex ) {
// $(row).attr('id', 'employee-'+data.id);
// }
};
// $(tableIdOrCss).remove();
var table = $(tableIdOrCss).DataTable(param);
return table;
}
I genrating column using server side data.
Columndefinition function:
function getColumnDefinition(year, month) {
var columns = [
{"sTitle": "ID", "mData": "e_id", "bSortable": true},
{"sTitle": "Employee Name", "mData": "employee_name", "bSortable": true},
];
var totalDay = getDayCount(year, month);
var monthS = month.slice(0, 3);
for (var i = 1; i <= totalDay; i++) {
if (i < 10) {
var date = '0' + i.toString();
}else {
var date = i.toString();
}
var dateColumn = {"sTitle": date + "-" + monthS, "mData": date, "bSortable": true};
columns.push(dateColumn);
}
return columns;
}
I am unable to find any solution
As you can see on DataTable documentation for destroy() method, in the case of column change, you should destroy datatable instance and remove all child nodes of the table element with jQuery#empty() call before adding new columns.
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
table.destroy();
$('#myTable').empty(); // empty in case the columns change
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );
Here it is the working example.

Datatables dynamically change on row but data object not change ajax

we coding a quotation form for our company and want to add products a datatable and changing value on it. After change data we send to controller but they same the first time. Here is datatable structure.
var selectedProduct = $('#selectedproduct').DataTable({
"columns": [
{
"orderable": false,
"data": "IsConfirm",
},
{ "orderable": false, "data": "Product.Id" },
{ "orderable": false, "data": "Product.Name" },
{ "orderable": false, "data": "Product.Description" },
{
"orderable": false,
"data": "Quantity",
"render": function (data, type, full, meta) {
return '<td width="100px"><input class="touchspinquantity" type="text" value="' + data + '" name="quantity"></td>';
}
},
{ "orderable": false, "data": "Product.SalePrice" },
{
"orderable": false,
"data": "Discount",
"render": function (data, type, full, meta) {
return '<td width="100px"><input class="touchspindiscount" type="text" value="' + data + '" name="discount"></td>';
}
},
{ "orderable": false, "data": "Product.Currency" },
{ "orderable": false, "data": null, "defaultContent": '' },
{
"orderable": false,
"data": null,
"defaultContent": '<button id="deleteproduct" class="btn btn-warning btn-circle" type="button"><i class="fa fa-times"></i></button>'
},
],
"createdRow": function (row, data, index) {
if (data.IsConfirm) {
$('td', row).eq(0).html('<input type="checkbox" checked class="i-checks" name="input[]">');
}
else {
$('td', row).eq(0).html('<input type="checkbox" class="i-checks" name="input[]">');
}
},
"searching": false,
"paging": false,
"bInfo": false,
"ordering": false
});
Here is how to get data
var datat = table.fnGetData();
You may need to redraw the datatable after the updation
selectedProduct.draw();
I solved problem but maybe that's not good way.
Here is the solve
var rows = table.fnGetNodes();
var arr = [[]];
for (var i = 0; i < rows.length; i++) {
var detaildata = [];
var cells = rows[i].cells;
detaildata[0] = cells[0].childNodes["0"].checked;
detaildata[1] = cells[1].innerText;
detaildata[2] = cells[2].innerText;
detaildata[3] = cells[3].innerText;
detaildata[4] = cells[4].firstChild.childNodes[1].value;
detaildata[5] = cells[5].innerText;
detaildata[6] = cells[6].firstChild.childNodes[1].value;
detaildata[7] = cells[7].innerText;
detaildata[8] = cells[8].innerText;
arr[[i]] = detaildata;
//var select = cells[0].children[0].value;
//if (cells[0].children[0].checked) {
// select = cells[0].children[0].value;
//} else {
// select = 'off';
//}
}

DataTable not Rendering corrrectly after xmlhttp.responseText

DataTable is showing but only after I change number of items per page. Similarly, pagination is only working if I search an item.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var col = [{
"mData": "row1"
}, {
"mData": "row2"
}, {
"bSortable": false,
"mData": null,
"sTitle": "Actions",
"bSearchable": false,
"mRender": function(data, type, full) {
return '<img alt="Download" src="https://upload.wikimedia.org/wikipedia/commons/e/e3/Ppbc_icon_download.png" title="Download"/>';
}
}];
var ss = JSON.parse(xmlhttp.responseText);
$('#myTable').dataTable({
"aaData": ss,
"aoColumns": col,
"bDestroy": true
});
}
};
Instead of aoColumns, used columns.
var col = [{
"mData": "row1",
"sTitle": "row1"
}, // <-- which values to use inside object
{
"mData": "row2",
"sTitle": "row2"
}, {
"bSortable": false,
"mData": null,
"sTitle": "Download",
"bSearchable": false,
"mRender": function(data, type, full) {
return '<img alt="Download" src="https://upload.wikimedia.org/wikipedia/commons/e/e3/Ppbc_icon_download.png" title="Download"/>';
}
}];
JSON.parse(xmlhttp.responseText);
var ss = $('#myTable').dataTable({
"aaData": ss,
"columns": col,
"bDestroy": true
});
}
};

jQuery Datatables.net - refresh table - getting null sAjaxSource

I have the following function which should update a datatable in my ASP.NET site master page:
function refreshTable(oTable) {
var table = $(oTable).dataTable();
var oSettings = table.fnSettings();
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(oSettings.sAjaxSource, null, function (json) {
table.fnClearTable(this);
for (var i = 0; i < json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
This function is then called to refresh a table if an attachment is added to the site - this is the datatable settings that it should refresh.
var DeleteClicked = false;
var oTable;
$(document).ready(function () {
oTable = $('#infoTable').dataTable({
"aaSorting": [[6, "desc"]],
"bProcessing": true,
"sAjaxSource": '/Web/Handlers/infoTableHandler.ashx',
"aoColumns": [
{ "mData": "ID", "bVisible": false },
{ "mData": "Type" },
{ "mData": "Received" },
{
"mData": "Action", "sWidth": "100px", "mRender": function (data, type, row) {
var id = row.ID;
return "<input type=button id=" + id + " onclick='DeleteFile(" + id + ")' class=buttonBlue value=Delete />";
},
},
{ "mData": "IsImage", "bVisible": false }
],
"bDeferRender": true,
});
However - if I open Developer Tools in Chrome I get an error message saying sAjaxSource is null so i cannot then get the value from it - so oSettings is null and then I cannot get access to the sAjaxSource - anyone see anything wrong here?
you're basically reinitializing your dataTable in the first row of refreshTable. Try instead:
function refreshTable() {
var oSettings = oTable.fnSettings();
...
}
and refer directly to the global oTable instead of your local table variable

Undefined Object in DataTable

Have a datatable and using the drill down row. The top row populate data but the link to drill down to the additional row contains a undefined object and I'm stuck right there.
Any help would be so appreciated. oData.code (undefinded) / oData itself will return everything from the linq query but when I start using the oData.etc... the object becomes undefined. Even in the click event I've tried to access oData and drop it in the second TD row and it to is also undefined.
function fnFormatDetails(oTable, nTr)
{
var oData = oTable.fnGetData(nTr);
var sOut =
'<div>' +
'<table>' +
'<tr><td> '+oData.code+' </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'
'</table>' +
'</div>';
return sOut;
} //end fnFormatDetails function
$(document).ready(function ()
{
var anOpen = [];
var oTable = $('#VADataTable').dataTable(
{
"sDom": 'T<"clear">lfrtip',
"oTableTools":
{
"sSwfPath": "/swf/copy_csv_xls_pdf.swf"
}, //flash must be enabled
"iDisplayLength": 5, //defalut amount of rows shown on page
"bServerSide": false, //uses sever for filter curently turned off
"bFilter": false, //makes columns clickable to filter
"bProcessing": true,
"bserverSide":false,
"bJQueryUI": true, //enables user interface
"bSort": true, //sorting for columns
"bScrollInfinite": true, //using this takes away ddl of selection
"sAjaxSource": "Data/IndustryTable", //where ajax commands renders results
"sScrollY": "200px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
"fnRowCallback": function (nRow, aData)
{
if (aData[0] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "sName": "code", "sTitle": "Code" },
{ "sName": "code" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" }
]
});
$('#VADataTable td.control').live('click', function ()
{
var nTr = this.parentNode;
var i = $.inArray(nTr, anOpen);
if (i === -1)
{
$('td').attr('+');
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
$('div', nDetailsRow).slideDown();
anOpen.push(nTr);
} //end if
else
{
$('td').attr('-');
$('div', $(nTr).next()[0]).slideUp(function ()
{
oTable.fnClose(nTr);
anOpen.splice(i, 1);
}); //ends slideUp
} //ends else
$('#new tr').after('<td> '+ typeof(oTable.code) +' </td>');
}); //ends click event
} //ends live event
)//ends ready function
I believe that just add the "mData" property in "aoColumns", that is the name of fields of database table, and in "fnRowCallback" you must replace "aData[0]" by "aData['code']" like the next example:
"fnRowCallback": function (nRow, aData)
{
if (aData['code'] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "mData" : "code", "sName": "code", "sTitle": "Code" },
{ "mData" : "code", "sName": "code" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" }
]

Categories

Resources