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
})
});
Related
I have two DataTables on the same web page with the same number of columns that are sourced from DIFFERENT APIs. If I add the class "grid" to one or the other the table displays with the correct data for that table. However, if I add the class "grid" to both, the data for the first table shows up on BOTH tables.
The class "grid" is a very complex DataTable that involves quite a bit of configuration but here is how "grid" is initialized:
var t = $(".grid").DataTable({
iDisplayLength: 10,
columnDefs: [{
"searchable": false,
"orderable": bOrderBy,
"targets": 0
}],
order: [[0, orderDir]],
ajax: {
url: src,
dataSrc: ""
},
columns: [
{
data: f1
},
{
data: f2
},
{
data: f3
},
{
data: f4
},
{
data: f5,
. . . "blah, blah, blah"
});
t.on('post-body.bs.table', function () {
$('[data-toggle="tooltip"]').tooltip({
container: 'body',
placement: 'top'
});
});
if (autoNum == "Y") {
t.on('order.dt search.dt', function () {
t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
}
How do I fix this?
Right now, it is applying the same DataTable instance to anything selected in your .grid selector which is why they are coming back the same. If the table options are the same, you can save this into a obj and then pass it to each call. Name the 2 tables with different id's or different classes
var dtOptions = {
iDisplayLength: 10,
columnDefs: [{
"searchable": false,
"orderable": bOrderBy,
"targets": 0
}],
order: [[0, orderDir]],
ajax: {
url: src,
dataSrc: ""
},
columns: [
{
data: f1
},
{
data: f2
},
{
data: f3
},
{
data: f4
},
{
data: f5,
. . . "blah, blah, blah"
};
$("#mytable1).DataTable(dtOptions);
$("#mytable2).DataTable(dtOptions);
You may need to change the ajax src for the 2nd table as you said they are coming from separate api's. You could possibly copy the options object and modify the ajax src if needed.
var dtOptions2= $.extend(true, {}, dtOptions);
dtOptions2.ajax.url = "somthing-else...";
$("#mytable2).DataTable(dtOptions2);
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.
How to create an edit link with function having multiple parameter from the data columns returned from ajax.
I read about the render callback but it only gets one column value & I need 2.
I need something like the following pseudo code.
"columnDefs": [ {
"targets": [0,1],
"data": "0,1",
"render": function ( data, type, full, meta ) {
return ``
}
} ]
As I'm disabling global search on all column except one. I cannot use the above code that use targets property. I don't know how to achieve this, please guide.
Edit: Complete code
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{ "searchable": false, "targets": [ 0,2,3,4,5,6,7,8,9,10,11 ] }
]
});
You can access row data using full variable, for example full[0] or full[1].
However instead of generating links in HTML, I would retrieve row data in a click handler as shown below:
$('#example').DataTable({
"columnDefs": [
{
"targets": [0, 1],
"render": function ( data, type, full, meta ) {
return 'Edit';
}
}
],
// ... other options ...
});
$('#example').on('click', '.btn-edit', function(){
// Get row data
var data = $('#example').DataTable().row($(this).closest('tr')).data();
edit(data[0], data[1]);
});
I needed Edit link on first column, so I followed #Gyrocode.com answer and it works great.
I also wanted to use the global search for searching but only on one column. Datatable ColumnDef Documentation gave me the clue so I ended up doing as follows.
Here The complete code:
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Edit';
}
},
{ targets: 1, searchable: true },
{ targets: '_all', searchable: false }
]
});
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/