datatable add class a td render - javascript

How Can I add a class in this render where I ask if the office is enable or disable, if this disable should add this class table-active. I was searching for some similar question but none worked.
var table = $('#tbl_1').DataTable({
"order": [
[1, "asc"]
],
"destroy": true,
"ajax": {
"method": "POST",
"url": "JSON/Office.php"
},
"iDisplayLength": 15,
"columns": [ {
"data": "Office",
"width": "20%"
}, {
"data": "Status",
"searchable": false,
"sortable": false,
"aling": "center",
"render": function(data, type, row) {
var Status = row["Status"];
if (Status == 'FALSE') {
return '<button class="btn btn-sm btn-success active" onclick="enable_item(this)"title="Active">Active</button>';
} else {
return '<button class="btn btn-sm btn-danger disable" onclick="disable_item(this)" title="Disable"> Disable</button>';
}
}
}],
"dom": '<"dt-buttons"Bf><"clear">lirtp',
"paging": true,
"autoWidth": true,
buttons: [{
extend: 'excel',
text: 'Excel'
}]
});
One of the answer I found was this $(row).addClass("table-active"); but still not working :(. I hope I explain well greetings

If I understood you correct and you want to add a class to the <tr> element you can use the createdRow hook - https://datatables.net/reference/option/createdRow.
$('#tbl_1').dataTable({
"createdRow": function( row, data, dataIndex ) {
if ( data["Status"] == false ) {
$(row).addClass( 'table-active' );
}
}
});

Related

How to show jQuery Datatable error in a bootstrap alert-warning div rather than the alert box

I am working on an ASP.NET Core 2.1 website and I am using Datatables.net to display my record lists retrieved from a backend API.
This issue I am trying to resolve is that, whenever an error occurs while retrieving the data from the backend API, I want the error message to appear in a Bootstrap alert-error DIV on the same page as the datatable.
I have looked at https://datatables.net/forums/discussion/30033/override-default-ajax-error-behavior and Enable datatable warning alert but I am not strong in javascript so I am having some difficulty determining how to implement this feature.
Currently, I have the datatable set up in my cshtml page as follows;
<script>
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Sites/LoadData",
"type": "POST",
"datatype": "json"
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>
And here is the loaddata action in my SitesController class;
public async Task<IActionResult> LoadData()
{
try
{
await SetCurrentUser();
ViewData["Role"] = _currentRole;
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
var pageSize = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var request = new SitesGetListRequest
{
OrderBy = SetOrderBy(sortColumn, sortColumnDirection),
Filter = SetFilter(searchValue),
PageNumber = (skip / pageSize) + 1,
PageSize = pageSize
};
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var endpoint = $"api/companies/{SetCompanyId()}/sites/filtered";
var siteData = await _client.GetSiteListAsync(request, endpoint, token);
if (siteData.Sites != null)
{
return Json(new
{
draw,
recordsFiltered = siteData.Paging.TotalCount,
recordsTotal = siteData.Paging.TotalCount,
data = siteData.Sites.ToList()
});
}
//TODO: Find a way to pass error to a Bootstrap alert-warning DIV rather than the jQuery (javascript) alert box
var errorMessage = $"Http Status Code: {siteData.StatusCode} - {siteData.ErrorMessages.FirstOrDefault()}";
return Json(new
{
data = "",
error = errorMessage
});
}
catch (Exception ex)
{
const string message = "An exception has occurred trying to get the list of Site records.";
_logger.LogError(ex, message);
throw;
}
}
As it stands right now, If an error exists in the object returned from the API call, I pass a message to the error property in the returned json and it shows up as an javascript alert popup box on my cshtml page and when I click OK, the datatable displays "No records found", as shown in the images below;
and...
What I want is for the error message to display in a bootstrap alert-danger div at the top of the cshtml page. I so not want the alert popup to appear and I still want the datatable to show "No records found".
I think that what I am looking for is described on Enable datatable warning alert...
Disable the alert popup by using
$.fn.dataTable.ext.errMode = 'none';
And pass the error message to the BootStrap div using
$('#example')
.on( 'error.dt', function ( e, settings, techNote, message ) {
console.log( 'An error has been reported by DataTables: ', message );
} )
.DataTable();
but instead of
console.log( 'An error has been reported by DataTables: ', message );
use something like
$("#error").html(MY ERROR MESSAGE HERE);
and assign id="error" to the bootstrap div.
But, I am having trouble figuring out how to trigger the Ajax call from my loaddata method in the SitesController and also how to correctly add the error event to the beginning of my datatable script.
Before I burn more time trying to work this out, I thought I would put this on SO and see if anyone with javascrit/jquery experience can provide some guidance.
You can add the error property to the ajax call. Probably the best will be to use fnServerData.
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"sAjaxSource": "/Sites/LoadData",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (data) {
fnCallback(data);
},
"error": function(error){
$("#error").html(error);
}
});
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>

error 500 on jquery datatables search

i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?

Disable selected rows in some rows of dataTable

I use DataTable for create a list. and I unable selected multirow in it.
when click on some first rows (page1 of table), rows was selected. but when click on other pages, rows was not selected and was not go to this script and dont show anything:
$("#example tbody tr").click( function( e ) {
console.log(e);
console.log( $(this).hasClass('selected'));
if ( $(this).hasClass('selected') ) {
console.log(1111111111);
$(this).removeClass('selected');
}
else {
console.log(222222222);
table.$('tr.selected')//.removeClass('selected');
$(this).addClass('selected');
}
});
my table:
Studentjson = {BrowserStats};
var data = jQuery.map(Studentjson.BrowserStats, function (el, i) {
return [[el.imagePath, el.firstName, el.lastName, el.homeLocationText, el.homePhoneNumber,
el.role, el.edit, el.delete]];
});
table = $('#example').DataTable({
"aaData": data,
columns: [
{
"width": "3%",
data: null,
className: "center",
"orderable": false,
defaultContent: '<img class="img-responsive" src="" />'
},
{"width": "27%"},
{"width": "27%"},
{"width": "37%"},
{
data: null,
"width": "3%",
className: "center",
"orderable": false,
defaultContent: '<p data-placement="top" data-toggle="tooltip" title="Edit"><button id="EditStudent" class="btn btn-primary btn-xs" data-title="ویرایش" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>'
},
{
data: null,
"width": "3%",
"orderable": false,
defaultContent: '<p data-placement="top" data-toggle="tooltip" title="Delete"><button id="DeleteStudent" class="btn btn-danger btn-xs" data-title="Delete" ><span class="glyphicon glyphicon-trash"></span></button></p>'
},
{
"visible": false,
"searchable": false
},
{
"visible": false,
"searchable": false
}
]
});
Why this is? What i must do?

Highlight specific row base on content in jquery datatables

I am using jquery datatables.net and I have a table with information. In the one column I have true or false values for whether the user is active or not. I am trying to get it so when the value is false, highlight the value. Right now my code for my table settings looks like this:
//Settings for datatable
$('#userTable').DataTable({
"jQueryUI": true,
"serverSide": true,
"ajax": {
"type": "POST",
url: "/Management/StaffGet",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { console.log(data); return data = JSON.stringify(data); }
},
"columns": [
{ "data": "employeeNumber" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "role" },
{
"data": "active",
},
{
"data": "employeeNumber",
"render": function (data, type, full, meta)
{
return 'Edit | Delete ';
}
}
],
"order": [[ 0, "asc"]],
"paging": true,
"deferRender": true,
"processing": true,
"stateSave": false,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"pageLength": 10,
"pagingType": "simple_numbers",
"searching": false,
"createdRow": function ( row, data, index ) {
if (data[4] == "false" ) {
$('td', row).eq(5).addClass('highlight');
}
}
});`
Then my code for css is:
`<style type="text/css">
td.highlight {
font-weight: bold;
color: red;
}
</style>`
I feel like there is a problem with the setting on the column, any help is appreciated.
Try
$('#userTable').DataTable({
...
"createdRow": function( row, data, dataIndex ) {
//console.log(data[4]);
if ( data[4] == "false" ) {
//console.log($(row).find("td").eq(4).html());
$(row).find("td").eq(4).addClass( 'highlight' );
}},
...
The commented log statements are in there to check you are getting and comparing the correct data.
Tested with datatables 1.10.1

JQuery DataTable add attribute to customize button

I'm trying to build JQuery DataTable with customize buttons. This is my code:
<table id="myDataTable" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "Home/GetDataTable",
"bProcessing": true,
"aoColumns": [
{"data": "ID"},
{ "data": "Name" },
{ "data": "Address" },
{ "mData": "Town" },
{
bSortable: false,
data: null,
className: "center",
defaultContent: '<button class="btn btn-danger data-id="" ">edit</button> <button class="btn btn-primary">delete</button>'
}
],
"columnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
},
]
});
});
</script>
And this is my Action in the Controller:
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = result.Count(),
iTotalDisplayRecords = result.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
This code works fine but now I want to add data-id attributes to my buttons. I wanna to set value of ID field (which I hided) to data-id attribute for each row. How I can implement it?
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "Home/GetDataTable",
"bProcessing": true,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
// if your button is in 5th column then index will be 4 because it starts from 1
$('td:eq(4)', nRow).find( 'button' ).attr('id',aData[0]);
//assuming your id is in the 1st element of data
},
"aoColumns": [
{"data": "ID"},
{ "data": "Name" },
{ "data": "Address" },
{ "mData": "Town" },
{
bSortable: false,
data: null,
className: "center",
defaultContent: '<button class="btn btn-danger data-id="" ">edit</button> <button class="btn btn-primary">delete</button>'
}
],
"columnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
},
]
});
});
</script>
hi could u please test this code :
{
bSortable: false,
data: null,
render: function(d) {
return "<button class="btn btn-danger data-id="'+ d.YourModelID +'" ">edit</button> <button class="btn btn-primary">delete</button>";
},
className: "center",
}
instead of this :
{
bSortable: false,
data: null,
className: "center",
defaultContent: '<button class="btn btn-danger data-id="" ">edit</button> <button class="btn btn-primary">delete</button>'
}

Categories

Resources