JQuery DataTable add attribute to customize button - javascript

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>'
}

Related

Show Check box in every row using JavaScript data table

Using the JavaScript datable get the data with pagination but i have to show checkbox on header and each row. once select the check box get the id of particular row or if select header checkbox get all rows id on server side.
Table :
<table id="tblSavingColl" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr style="background-color: Mediumseagreen">
<th>#Html.CheckBox("CheckAll") </th>
<th>Shop</th>
<th>Client ID</th>
<th>Sales Month</th>
<th>Control</th>
<th>Entry</th>
<th>TMS</th>
<th>Informed</th>
<th>Posted</th>
</tr>
</thead>
<tbody id="tblData">
</tbody>
</table>
Javascript:
$("#btnList").click(function () {
var Buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
var Post = $("#SelectedValue").val();
$("#tblSavingColl").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Archive/GetArchiveList",
"type": "POST",
data: { buildingid: Buildingid, shopid: shopid, Post: Post },
"datatype": "json"
},
"columnDefs": [{
'targets': 0,
'checkboxes': {
'selectRow': true
}
//"targets": [0],
//"visible": false,
//"searchable": false,
//'render': function (data, type, full, meta) {
// return '<input type="checkbox" name="id[]" value="'
// + $('<div/>').text(data).html() + '">';
//}
}],
" select": {
'style': 'multi'
},
"order": [[1, 'asc']],
"columns": [
{"data": "id","defaultContent": '',"className": 'select-checkbox',"orderable": true},
{ "data": "shopName", "name": "ShopName", "autoWidth": true },
{ "data": "clientID", "name": "clientID", "autoWidth": true },
{ "data": "salesMonth", "name": "salesMonth", "autoWidth": true },
{ "data": "controlTotal", "name": "controlTotal", "autoWidth": true },
{ "data": "totalAmount", "name": "totalAmount", "autoWidth": true },
{ "data": "tms", "name": "tms", "autoWidth": true },
{ "data": "informed", "name": "informed", "autoWidth": true },
{ "data": "posted", "name": "posted", "autoWidth": true },
//{
// "render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
//},
//{
// data: null,
// render: function (data, type, row) {
// return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
// }
//},
]
});
});
I have used this javascript url and also tried to use data table
JS url:
<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" />
<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>

datatable add class a td render

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' );
}
}
});

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?

Datatable aoColumnDefs is not working as expected

I am facing an issue with Datatable .
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th>${column.columnTitle}</th>
</c:forEach>
</tr>
</thead>
<tfoot>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th></th>
</c:forEach>
</tr>
</tfoot>
<tbody>
<c:forEach items="${Details.callList}" var="call">
<tr>
<c:forEach items="${call.attributes}" var="attribute">
<td>${attribute.value}</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
$("#example1").dataTable({
'sDom': '"top"i',
//"aoColumnDefs": [{ "bSearchable": true, "aTargets": [1] }],
"bPaginate" : true,
"bLengthChange" : false,
//"bFilter" : true,
"bSearchable": true,
"bSort" : true,
"bInfo" : true,
"bAutoWidth" : false,
"iDisplayLength": 5
//}).columnFilter({"aoColumns": [{ "type": "text" }, { "type": "text" }, null]});
}).columnFilter({"aoColumnDefs": [{ "bSearchable": true, "aTargets": [2] }]});
From the above snippet.. i am trying to remove the filter/search for last column alone.
Here "aoColumns" works as expected - It removes the filter in last column as i coded,
However i am unable to use "aoColumns" . Since the columns in this table is dynamic/configurable, so it is tough for me to change the code everytime.
It would be really grateful if anyone can help me here..
Thanks,
This is how I use Datatables and it works like a charm. I don't do sorting at client-side, I do it at server-side using AJAX, but the configuration for the table should be the same except for "bServerSide=true". Let me know if this solves your problem:
var oTable = $('#tblMainTable').dataTable({
"searching": false,
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('jobTitlesDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('jobTitlesDataTables'));
},
"pagingType": "full_numbers",
"bLengthChange": false,
"bAutoWidth": false,
"iDisplayLength": 2000,
"bServerSide": true, // server side
"sAjaxSource": BASE_URL + "Job/GetJobTitleMappingDTOs", // AJAX URL
"bProcessing": true,
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
// send data from client-side to server-side
aoData.push({ "name": "IsMapped", "value": $("#bdgIsMapped").data("selected") });
aoData.push({ "name": "IsSearchableOption", "value": $("#bdgIsSearchable").data("selected") });
aoData.push({ "name": "timestamp", "value": new Date().getTime() }); // Added to avoid caching in some IE versions.
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (json) {
// shows records count next to the top title
if (json.iTotalRecords > 0) {
$("#resultsDescription").text(" - " + json.iTotalRecords + " rows.");
}
else {
$("#resultsDescription").text(" - No results.");
}
// shows paginator when necessary
if (json.iTotalRecords > json.iDisplayLength) {
$(".dataTables_paginate").show();
}
else {
$(".dataTables_paginate").hide();
}
$("#isFirstSearch").val("false");
fnCallback(json);
}
});
},
"aoColumnDefs": [
{
sType: "numeric",
mData: "RowNumber",
aTargets: [0],
mRender: function (data, type, full) {
// this is for custom rendering a column just in case you need it
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="RowNumber">' + full.RowNumber + '</span>';
}
},
{
sType: "numeric",
mData: "JobTitleId",
aTargets: [1],
mRender: function (data, type, full) {
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="EditableJobTitleId" data-job-title-id="' + full.JobTitleId + '">' + full.JobTitleId + '</span>';
}
},
{
sType: "string",
mData: "JobTitle",
aTargets: [2]
}
],
"order": [[1, "asc"]]
});

DataTable Error - Cannot read property 'length' of undefined

I am trying to build my DataTable (1.10.5) using an ajax call to a service - http://www.datatables.net/examples/ajax/
Here is my Javascript:
$('#tableexample').DataTable({
"dom": 'C<"clear">lfrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../../api/EventTypes/GetAll",
"aoColumnDefs": [
{
"aTargets": [0],
"mData": "Id"
},
{
"aTargets": [1],
"mData": "Name"
},
{
"aTargets": [2],
"mData": "Name"
},
{
"aTargets": [3],
"mData": "Name"
},
{
"aTargets": [4],
"mData": "Name"
}
]
});
Here is my HTML:
<table id="tableexample" class="table table-striped dataTable table-hover">
<thead>
<tr>
<th>Select</th>
<th>Event</th>
<th>Primary Category</th>
<th>Secondary Category</th>
<th>Workflow</th>
</tr>
</thead>
</table>
Here is my error:
Uncaught TypeError: Cannot read property 'length' of undefined
If I look i my jquery.dataTables.js - it says that my data is undefined...
var data = _fnAjaxDataSrc( settings, json );
Can anyone help me out with setting up my ajax call properly to dynamically build my table??
Thanks!
Finally found it!
I needed to make an ajax call and pass the data to "aaData":
$.ajax({
url: '/Portal/api/EventTypes/GetEventWorkflowDefinitions',
type: 'GET',
dataType: 'json',
success: function (data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#tableexample').dataTable({
"dom": 'C<"clear">lfrtip',
"bAutoWidth": false,
"aaData": data,
"aaSorting": [],
"aoColumnDefs": [
{
"aTargets": [0],
"bSearchable": false,
"bSortable": false,
"bSort": false,
"mData": "EventTypeId",
"mRender": function (event) {
return '<input class="childCheck" type="checkbox" id="childCheckBoxes" value="' + event + '">';
}
},
{
"aTargets": [1],
"mData": "EventType"
}
Once I did this...the table build perfectly!

Categories

Resources