I am trying to poulate dataTable with my Server Side Values but its not getting populated correctly.I am Posting my dataTable Structure code..
dt = $("#up").dataTable({
"data": dataSet,
"paging": false,
"responsive": true,
"stateSave": true,
"columns": [
{ "title": "<input type='checkbox' id='selectAll'>", "bSortable": false, "width": "5px", },
{ "title": "", "bSortable": false, "width": "5px" },
{ "title": "Code", "width": "50px" },
{ "title": "Name" },
{ "title": "Contact Name" },
{ "title": "Contact Email" }
]
});
In the above Table , i want first column as Select All checkbox type and second column as edit column with edit(Pencil) icon and rest of the columns with my Server Side Values but currently the data from server side is getting displayed right from first column keeping last two columns empty ..Also i am getting this alert as Warning DataTables warning: table id=CompanySetup - Requested unknown parameter '4' for row 0. For more information about this error, please see http://datatables.net/tn/4
Please help me to get it ..Thanks..
Update..
#{
StringBuilder sb = new StringBuilder();
foreach(row in model.MyTable)
{
sb.AppendFormat("['{0}', '{1}', '{2}', '{3}'],",
row.Field1, row.Field2, row.Field3, row.Field4);
}
}
var dataSet = [#Html.Raw(sb.ToString())];
Related
I have a datatable that retrieves json data from an api. The first column of the table should only contain a checkbox. However, when retrieving the data it populates the first column as well.
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
$('#parametrictable').DataTable({
data : json.data,
columns : json.columns,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
})
});
Is there any way that I can set that the data should only populate starting from the second column, leaving the first column to only contain the checkbox?
You can fix this issue by updating the api or in your js code just updating the data key value to null for first object in the json.columns array like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
json.columns[0].data = null;
json.columns[0].defaultContent = '';
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
.... your rest of code
})
});
EDIT:
I meant what your suggestion only did was hide the data that was overlapping with the checkbox. I don't want it hidden. I want the first column to be, by default, only checkboxes. and the overlapping data should be on the 2nd column.
You can update your API like this to achieve that:
"columns": [
{
"data": null,
"defaultContent": ""
},
{
"data": "DT_RowId",
"title": "Id"
},
{
"data": "supplier",
"title": "supplier"
},
{
"data": "color",
"title": "color"
}
],
Or, you can update your code without modifying your API like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
// Add object for checkbox at first position
json.columns.unshift({"data": null, "defaultContent": ""});
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
....your rest of code
})
});
I have a js data table that I have implemented for pagination of data. It uses the jQuery data table. The data is being displayed correctly. However, I want to add an element within the first row of the data table.
Before I added it like this : <td>#Html.ActionLink(item.CarId, "Detail", "Cars", new { id = item.CarId},null)
<span class="dt-expand-btn js-expand-btn">+</span></td>
What I want to add within the td of the js is : <span class="dt-expand-btn js-expand-btn">+</span>
var carsDataTable = $('.js-cars-lists').DataTable({
"ajax": {
"url": "/Cars/CarsPagination",
"processing": true,
"serverSide": true,
"language": {
"paginate": {
"previous": '<i class="material-icons">chevron_left</i>',
"next": '<i class="material-icons">chevron_right</i>'
}
},
"order": [0, "asc"],
"type": "POST",
"datatype": "json"
},
"columns": [
{
"data": "CarId", "name": "CarId", "autowidth": true,
"render": function (data, type, row, meta) {
$(row.CarId).css('color', 'red');
return '' + row.CarId + '';
}
},
{ "data": "CarName", "name": "CarName", "autowidth": true },
Could someone please help me to achieve this ? Also, paginate icons are not appearing. Please help.
jQuery DataTable has a function of render it accepts 4 parameters function(data, type, row) which you can control the rendering of your rows. You can now check the rows of a table and add your element in it.
You can use columnDefs method and then render:
...
columnDefs: [{
"render": function(data, type) {
return '<span class="dt-expand-btn js-expand-btn">+</span>';
},
"targets": 0
}]
...
targets refers to the index of the table column (since you are referring to the 1st column) set it to 0
I am using Jquery Data-table and binding the Large unsorted object data to datatable. My code is below:
var ExpenceDataTableElement = $('#ExpenceDataTable').DataTable({
data: Data,
pageLength: 10,
"bSort": false,
"autoWidth": false,
columns: [{
"className":"clsAction",
"data": "TimesheetUID",
"title": "Action",
"render": (data, type, row) => '<input class="checkbox" type="checkbox" />',
"width": "4%",
"visible":true
},
{
"className":"clsPeriodName",
"data": "PeriodName",
"title": "Timesheet Name",
"visible":true
},
{
"className":"clsTSPeriodStatus",
"data": "Open",
"title": "Timesheet Period <br> Status",
"render":function(data,type,row){ if(data == 1){return " Open"}else{return " close"}},
"width": "10%",
"visible":true
}
],
"oLanguage": {
"sEmptyTable": "No Records found."
}
});
The data contains more than 15 thousands of records, it contains the flag like 'Open' OR 'Close'. Currently I am using the for loop to sort the data and bind it to the data - table. Means if data have 15 thousand of records and it contains 7 thousands of 'Open' flag records, it takes long time to sort & bind the data to Datatable. Hence Is there any way to check the condition in 'columns:' if flag is not 'Open' then continue to the next iteration??
You could use the filter method to first filter the objects with 'open' status in the array.
someObject.columns.filter(x => x.data == 'open')
This will filter out only those with the flag 'open'. You can cache it into a variable for further work.
I am trying to include an invisible column in a jQuery DataTable that can be set to default true in place of a null or undefined encountered in the data source.
Say I am working with a 6-columns DataTable. The first 5 columns are visible. The 6th column is set to not be visible. And it must contain either a true or false, regardless of whether the data source object has the corresponding key. In the column definitions for the DataTable, I tried this but it did not work.
{ "defaultContent": true, "data": "existing", "visible": false }
According to the API, I think defaultContent works only when data is null. Maybe that's why it does not work. I have provided the HTML, JS data and JS code for initializing the DataTable. Notice that once the DataTable is loaded and rendered, I dynamically append a row and re-draw. The data for this row contains the 6th column property and that is gets set just fine.
HTML:
<div id="demo">
</div>
JavaScript (data initialization):
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
JavaScript (DataTable creation and initialization):
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
Here is the JSFiddle for the above example. If you click on the Select button in the first two rows, it returns undefined. The Select button on the third row yields false. I want the first two rows' Select button to yield true.
How do I set a default value for the 6th (invisible) column if no key/value is provided in the data-set object?
It returns undefined because existing not exists in dataSet. dataSet is static, defaultContent does not populate its value to the original dataSet. What you really want is the value of the hidden column, which will contain either defaultContent or dynamically added existing values.
var row = $('#example').DataTable().row( $(this).parents('tr') ),
index = row.index(),
data = row.cell(index, 6).data();
alert(data);
will return true, true and false. Forked fiddle -> http://jsfiddle.net/vsx7uxnf/
I have an issue with the reinitialisation of my datatable. My code below works by pulling in a json from getOrderStatus.php and upon success of this puts all the json data into javascript variables and then from this i can set these variables to div tags and display the data i need on my webpage. However the Datatable cannot be reinititalised once the ajax loop runs and displays the following error message "DataTables warning: table id=mytable - Cannot reinitialise DataTable". I believe i need a way to kill the table and recreate it upon the ajax refresh however i cant seem to find a way to do this ?
$(document).ready(function ajaxLoop(){
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function updateOrder(data) //on reciept of reply
{
var OrdersSubmitted = data.OrderStatus[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data.OrderStatus[0].FULFILLED; //get Orders Fulfilled count
var LastTransaction = data.LastTransaction[0]; //get Last Transaction
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html(OrdersSubmitted);
$('#OrdersFulfilled').html(OrdersFulfilled); //Set output html divs
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
setTimeout(ajaxLoop, 2000);
}
});
});
Did you try using "bDestroy": true.
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"bDestroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
Another way is if you check if datatable is already init. on your table
var table = $('#mytable');
if ($.fn.DataTable.fnIsDataTable(table)) {
//It's already a datatable
//clear and destroy
table.dataTable().fnClearTable();
table.dataTable().fnDestroy();
}
**It seems your are using latest datatable version:**
then option should be destroy:true (aging should be changed to paging):
$('#mytable').dataTable({
"data": LastTransaction,
"paging": false,
"searching": false,
"destroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
and check on existing datatable would be:
if($.fn.DataTable.isDataTable("#myTable"))
{
$('#myTable').DataTable().clear().destroy();
}