I have a table of orders,
filtering, sorting and records per page is done via server side.
How can i make the filtering of the status with the checkbox (see attached screenshot) work?
When changing entries number or searching in searchbox or sorting the action that retrieve the data is triggered (GetList()) , i want to trigger it when check\Uncheck one of the checkbox status.
My Action :
public ActionResult GetList()
{
//Server Side parameters
int start = Convert.ToInt32(Request.Form["start"].FirstOrDefault());
int length = Convert.ToInt32(Request.Form["length"].FirstOrDefault());
string searchValue = Request.Form["search[value]"].FirstOrDefault();
string sortColumnName = Request.Form["columns["+Request.Form["order[0][column]"]+"][name]"].FirstOrDefault();
string sortDirection = Request.Form["order[0][dir]"].FirstOrDefault();
List<Order> orderList = new List<Order>();
orderList = _unitOfWork.Order.GetAll().ToList();
int totalRows = orderList.Count;
foreach (Order order in orderList)
{
order.StringDate = order.UsDate.Day + "/" + order.UsDate.Month + "/" + order.UsDate.Year;
}
//
//filtering done here
//
int totalRowsAfterFiltering = orderList.Count;
//
//Sorting done here
//
//orderList = orderList.OrderBy(x => x.Id //sortColumnName + " " + sortDirection).ToList<Order>();
orderList = orderList.Skip(start).Take(length).ToList<Order>();
foreach (Order order in orderList)
{
order.AllowComplaint = allowComplaint(order.Id.ToString());
}
return Json(new { data = orderList, draw = Request.Form["draw"], recordsTotal = totalRows ,
recordsFiltered = totalRowsAfterFiltering});
}
Javascript\Ajax call the Action :
<script>
$(document).ready(function () {
$('#tblData').DataTable({
"ajax": {
"url": "OrderAdmin/GetList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "id", "name": "Id" },
{ "data": "orderStatus", "name": "OrderStatus" },
{ "data": "productName", "name": "ProductName" },
{ "data": "stringDate", "name": "StringDate" },
{ "data": "userNameToShow", "name": "UserNameToShow" },
{ "data": "storeName", "name": "StoreName" },
{
"data": "quantity", "name": "Quantity", "render": function (data) {
if (data > 1)
return `<div class="text-center" style="font-weight:bold;background-color:darkseagreen"><label >${data}</label></div>`
else
return `<div class="text-center"><label>${data}</label></div>`
}
},
{ "data": "cost", "name": "Cost" },
{
"data": "fullAddress", "name": "FullAddress", "render": function (data) {
return `<textarea readonly>${data}</textarea>`
},
"width": "20%"
},
{ "data": "trackingNumber", "name": "TrackingNumber", "width": "200px"},
{
"data": {
"orderStatus": "orderStatus",
"id": "id",
"allowComplaint": "allowComplaint"
},
"render": function (data) {
if (data.orderStatus == 'Accepted') {
return `
<div class="text-center">
<a href="/Admin/OrderAdmin/UpdateOrder/${data.id}" class="btn btn-success text-white" style="cursor:pointer">
<i class="fas fa-edit"></i>
</a>
</div>
`}
else if (data.orderStatus == 'Done' && data.allowComplaint) {
return `
<div class="text-center">
<a href="/Admin/Complaints/AddComplaint/${data.id}" class="btn btn-info text-white" style="cursor:pointer">
<i class="fas fa-ticket-alt"></i>
</a>
</div>
`
}
else { return `<div></div>` }
}, "width": "5%"
}
],
"serverSide": "true",
"order": [0, "desc"],
"processing": "true"
});
});
</script>
Actually i am facing a little bit problem. I want to show Edit and Delete Button in one column But I am unable to do that. Let me share my code with you.
var dataTable;
$(document).ready(function () {
dataTable = $("#tableId").DataTable({
"ajax": {
"url": "/Home/GetAllStock",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Stock_Name", "autowidth": true },
{ "data": "Stock_UOM", "autowidth": true },
{
"data": "Stock_ID", "width": "50px", "render": function (data) {
return '<button class="btn btn-success" onclick="geteditstock(' + data + ')">Edit</button> <button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button>'
}
},
{
"data": "Stock_ID", "width": "50px", "render": function (data) {
return '<button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button>'
}
}
]
});
});
I want Edit and Delete button show in one column adjacent to each other.
and my output is look like this.
Change width from 50px to atleast 200px, remove the last column which is of no use and wrap the two buttons in a div. Hope this helps!.. Happy Coding!!
var dataTable;
$(document).ready(function () {
dataTable = $("#tableId").DataTable({
"ajax": {
"url": "/Home/GetAllStock",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Stock_Name", "autowidth": true },
{ "data": "Stock_UOM", "autowidth": true },
{
"data": "Stock_ID", "width": "250px", "render": function (data) {
return '<div><button class="btn btn-success" onclick="geteditstock(' + data + ')">Edit</button> <button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button></div>'
}
}
]
});
});```
HTML :
<div class="datatable-header">
<button type="button" name="add" id="add" class="float-right btn btn-info">Add</button>
</div>
<div class="table-responsive">
<table class="table datatable-basic table-striped table-hover table-bordered"
data-data-url="<?= $this->url('bla/blabla/ajax', ['action' => 'list']) ?>
id="text-dataTable"
>
<thead>
<tr>
<th>Text</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
JQuery:
const textTable = $('#text-dataTable');
const textDataTable = textTable.DataTable({
"lengthMenu": [[10, 25, 50, 75, -1], [10, 25, 50, 75, "All"]],
"dom": '<"top"fBr><"datatable-scroll-wrap"t><"bottom mt-2"ilp>',
"lengthChange": true,
"pageLength": 25,
"autoWidth": false,
"searching": false,
"order": [[0, 'asc']],
"ajax": {
"url": textTable.data('data-url'),
"type": "POST"
},
"columnDefs": [
{ targets: [1], className: "text-center"},
],
"columns": [
{ data: "text", "render": function (data, type, full, meta) {
return '<textarea style="width: 100%" contenteditable id="text" class="update" data-id="'+full.id+'" data-column="text">' + data + '</textarea>';
}
},
{ data: "textId", "render": function (data, type, full, meta) {
let $html = '<a class="btn bg-success m-1 update" data-id="'+data+'"><i class="icon-floppy-disk"></i> Update</a>';
$html += '<a class="btn bg-danger m-1 remove" data-id="'+data+'"><i class="icon-trash"></i> Delete</a>';
$html += '<a class="btn bg-grey m-1 reset" data-id="'+data+'"><i class="icon-reset"></i> Reset</a>';
return $html;
}
},
],
"rowCallback": function (row, data, index) {
if (data.hasOwnProperty('rowClass')) {
$(row).attr('class', data.rowClass);
}
$('td:last', row).attr('class', 'text-center');
}
});
$('#add').click(function(){
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
}
);
textDataTable.draw( false );
const addedRowNode = addedRow.node();
$(addedRowNode).addClass('highlight');
});
Result:
it's updating the text for the first column and the data-id of the second column, my goal is to add a new empty row, which means i want the first column to have 'aa' and the second column to have 'bb' instead of the buttons. I tried hundreds of things in vain.
See Screenshot:
Second Thing I tried: which is a problem because if the user adds multiple rows at the same time and click insert one by one, it will always insert the value of the first new row added, since it's getting the value by id. And all the new rows have the same ID.
$('#add').click(function(){
let html = '<tr>';
html += '<td><textarea contenteditable id="new-row-text">aa</textarea></td>';
html += '<td><a class="btn bg-grey m-1 insert"><i class="icon-plus22"></i> Insert</a></td>';
html += '</tr>';
$('#text-dataTable tbody').prepend(html);
});
textDataTable.on('click', 'a.insert', function(){
swal.fire({
title: 'Are You Sure?',
showCancelButton: true,
confirmButtonClass: "btn-success",
reverseButtons: true,
showLoaderOnConfirm: true,
preConfirm: function (data) {
return new Promise(function (resolve, reject) {
$.post(
textDataTable.data('insert-url'),
{
text: $('#new-row-text').val()
},
(function data($data) {
resolve()
}),
'json'
).fail((function(xhr, status, error) {
swal.fire('Error', xhr.responseJSON.error, 'error');
}));
})
}
}).then(result => {
if (result.value) {
textDataTable.ajax.reload();
} else {
}
}, (function () {
}));
});
Solution:
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
"newRow": true
}
);
Then in the render function test to see if the newRow flag exists:
{ data: "textId", "render": function (data, type, full, meta) {
// Return data if new row
if (full.hasOwnProperty('newRow') {
return data;
}
.
.
},
Credit User 2Fkthorngren: https://datatables.net/forums/discussion/61522/problem-with-adding-new-empty-row/p1?new=1
I want to add a button to the column Action but I cant put the value of data-activateUser= item["AspNetUserId"]. I am jusing a plugin DataTables btw.
My Table
DataSource
$.getJSON("/Account/InactiveAccounts").then(function (items) {
var item = items;
console.log(item["UserAccounts"]);
$('#inactive-accounts').DataTable({
columnDefs: [{ targets: 'no-sort', orderable: false }],
data: item["UserAccounts"],
"processing": true,
columns: [
{ data: "Username" },
{ data: "Password" },
{ data: "Email" },
{
data: function () {
return `<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser=`+ item["AspNetUserId"] +`>Activate</button>
`;
}
}
]
});
JSON Data
Please change your
data: function () {
return `<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser=`+ item["AspNetUserId"] +`>Activate</button>`;
}
to
render: function (data, type, row, meta) {
return '<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser="'+ row.AspNetUserId +'">Activate</button>';
}
For further details about renderers, please check this
I am newbie for DataTables. I want to add button on each row for edit and delete(like below image)
I have tried with code:
Test.cfm
<table id="myDataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>UserID</th>
<th>Name</th>
<th>UserName</th>
<th>Passowrd</th>
<th>Email</th>
<th>IsActive</th>
<th>Command</th>
</tr>
</thead>
<tbody>
</tbody>
$(document).ready(function () {
var oTable = $('#myDataTable').dataTable({
// "bServerSide": true,
"sAjaxSource": "fetchUserData.cfm",
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mData": null },
{ "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
{ "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
{ "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%" },
{ "mData": "Email","sTitle": "Email" , "sWidth": "20%"},
{ "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
{
"mData": null,
"bSortable": false,
"mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
}
]
});
} );
fetchUserData.cfm
{
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
[
"2",
"arun singh",
"arun",
"arun",
"arunsingh#test.com",
"0",
""
],
[
"9",
"s s",
"sam3",
"sam3",
"ss#s.com",
"0",
""
],
[
"10",
"sameek mishra",
"sam56",
"sam",
"same#s.com",
"0",
""
],
[
"11",
"narendra kumar",
"narendra",
"nav",
"sa#sa.com",
"1",
""
],
[
"12",
"test test",
"test",
"test",
"test2#test.com",
"1",
""
]
]
}
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered.
I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype (can be ignored mostly)
full = The full data array for this row.
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
var table =$('#example').DataTable( {
data: yourdata ,
columns: [
{ data: "id" },
{ data: "name" },
{ data: "parent" },
{ data: "date" },
{data: "id" , render : function ( data, type, row, meta ) {
return type === 'display' ?
'</i>' :
data;
}},
],
}
}
take a look here... this was very helpfull to me
https://datatables.net/examples/ajax/null_data_source.html
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
I contribute with my settings for buttons: view, edit and delete.
The last column has data: null
At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
enter image description here
Take a Look.
$(document).ready(function () {
$('#datatable').DataTable({
columns: [
{ 'data': 'ID' },
{ 'data': 'AuthorName' },
{ 'data': 'TotalBook' },
{ 'data': 'DateofBirth' },
{ 'data': 'OccupationEN' },
{ 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
],
bServerSide: true,
sAjaxSource: 'EmployeeDataHandler.ashx'
});
});
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
well, i just added button in data.
For Example,
i should code like this:
$(target).DataTable().row.add(message).draw()
And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!