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
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
})
});
the btnSearchName will open a Modal with table of the search result, then it has checkbox per row to select, then after I click the btnSubmit, the Modal will close and must put the selected ssn_or_tin column in an input field like '123, 645, 936, 743', I already tried many codes but not working, please help
$('#btnSearchName').on("click", function() {
Namestable = $('#NamesDatatable').DataTable({
"processing": true,
'select': {
'style': 'multi'
},
'order': [[1, 'asc']],
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
defaultContent: '',
className: 'select-checkbox',
'checkboxes': {
'selectRow': true
},
orderable: false
},
{ "data": "ssn_or_tin", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
});
$('#btnSubmit').on("click", function () {
var rows_selected = Namestable.column(0).checkboxes.selected(); //i have not tested this line of code yet if it's working,
maybe there is another way of getting the selected checkbox, maybe by their class if they have the 'selected' class
$.each(rows_selected, function () {
$('#txtSSNTIN').append(
//I don't know what code to put here, it must append the
'ssn_or_tin' values like '123, 953, 673' in the input field with
the id 'txtSSNTIN'
);
});
});
You could have try Onrowbound in DataTable. You dont have to specify these things
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 want to create a Datatable with the JQuery Datatable library, but for beautification and UI reasons, I want an icon to change according to another input field. Lets say,
If td.field 4 is null then td.field 5 icon=1 else icon=2.
You are not going to add an Icon you are going to add a CSS Class and in the CSS class you are going to add the image you want.
Assuming you have made you ajax call and you have the JSON and you are creating the datatable.
table = $('#table').DataTable( {
"columns": [
{ "className":'userName col-md-2', "data": "userName" },
{ "className":'desc col-md-2', "data": "desc" },
{ "className":'timeStart col-md-2', "data": "timeStart" },
{ "className":'timeEnd col-md-2', "data": "timeEnd" },
{ "className":'dispatcher col-md-2', "data": "dispatcher" },
{
"className": 'edit',
"orderable": false,
"data": null,
"defaultContent": ''
},
],
"order": [[2, 'desc']], !NOT FINISHED YET
Immediate after this and before the table.row.add you have to create seperately the createdRow with the Icon you want to manipulate.
Inside the table section you add the statement you want to make for the createdRow.
"createdRow": function ( row, data, index ) {
if ( data.dispatcher == null ) {
$('td', row).eq(5).addClass("edit-incident2");
}else{
$('td', row).eq(5).addClass("edit-incident");
}
}
After this your code would look like the below witch is the fully table code.
table = $('#table ').DataTable( {
"columns": [
{ "className":'userName col-md-2', "data": "userName" },
{ "className":'desc col-md-2', "data": "desc" },
{ "className":'timeStart col-md-2', "data": "timeStart" },
{ "className":'timeEnd col-md-2', "data": "timeEnd" },
{ "className":'dispatcher col-md-2', "data": "dispatcher" },
{
"className": 'edit',
"orderable": false,
"data": null,
"defaultContent": ''
},
],
"order": [[2, 'desc']],
"createdRow": function ( row, data, index ) {
if ( data.dispatcher == null ) {
//console.log(data.dispatcher);
$('td', row).eq(5).addClass("edit-incident2");
}else{
$('td', row).eq(5).addClass("edit-incident");
}
}
} );
Then you draw your table and the statement makes the job.
table.row.add( {
"userName": responsejson.userName,
"desc": responsejson.desc,
"timeStart": responsejson.timeStart,
"timeEnd": responsejson.timeEnd,
"dispatcher": responsejson.dispatcher,
"_id": responsejson._id,
} ).draw();
The two CSS classes would look like this
td.edit-incident {
background: url('../img/incident_management.png') no-repeat center center;
cursor: pointer;}
td.edit-incident2 {
background: url('../img/incident_management2.png') no-repeat center center;
cursor: pointer;}
It is not something incredible fantastic but it took me some hours, and I think the result is nice and very easy for the user to immediately understand what is he looking.
"columns": [
{
"className": 'details-control', "orderable": false, "data": null,"defaultContent": '', "render": function (data, type, row) {
if(data.id==1)
return '<span class="glyphicon glyphicon-remove"></span>';
else
return '<span class="glyphicon glyphicon-ok"></span>';
},
}
]
just modify the column value before render.it's also possible to directly add the icon into datatable with the help of above code
giv ids for each row and tds
<tr id="1">
<td id="1"></td>
<td id="2"></td>
<td id="3"></td>
</tr>
if you creating <td> dynamically using the database
for(i=0;i<upto number of tds in a row;i++)
{
if($('#'+i).text()!='')//find td is null or not
{
$('#'+i).append('if');
}
else
{
$('#'+i).append('else');
}
}
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();
}