Generate button in dataTables from column value - javascript

I use datatable to render column and rows fron a json.
data variable is the json.
"columns" : [
{ "data" : "id" },
{ "data" : "username" },
{ "data" : "email" },
{ "data" : "site" },
{ "data" : "author_name" },
{ "data" : "user_name" },
{ "data" : "city" },
{ "data" : "region" },
{ "data" : "added" },
{ "data" : "member_status" },
{ "data" : "its_username" },
{ "data" : "register_date" },
{"defaultContent": "<a href='/admin/edit_recruited_user/' class='btn btn-primary'><i class='fa fa-edit'></i></a><a href='/admin/delete_recruited_user/' class='btn btn-danger'><i class='fa fa-trash'></i></a>"}
],
I am trying to add the value from id to my link /admin/edit_recruited_user/
Have any ideea if i can achieve this or i should rethink the datatables code ?

Add columnDefs.
See documentation https://datatables.net/reference/option/columns.render
$.getJSON('https://api.myjson.com/bins/1u28t', function(json) {
$('#example').DataTable({
data : json.data,
columns : [
{ data : 'Id' },
{ data : 'Name' },
{ data : 'Alias' }
],
columnDefs: [ {
"targets": 0,
"data": "download_link",
"render": function ( data, type, row, meta ) {
return '<i class="fa fa-edit"></i><i class="fa fa-trash"></i>';
}
}]
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<table id="example"/>

Related

Reset Search Results

Good morning. I made a data search & filter with datatables and it worked .. but when I moved the page and returned to that page the data was still stuck (not reset). In view I made it like the following image:
and in the js file I made it like this
brandmanage = $('#brandmanage').DataTable({
dom : 'rtpi',
pageLength: {{ $limit ?? '10' }},
language : {
paginate : {
previous : '<i class="fa fa-angle-left"></i>', // or '←'
next : '<i class="fa fa-angle-right"></i>', // or '→'
},
},
processing : true,
drawCallback : function( settings ) {
$('#lengthInput option[value={{ $limit ?? '10' }}]').attr('selected','selected');
},
serverSide : true,
stateSave : true,
ajax : {
url : "{{ route('lms.brand.getdata',['pfx'=>$pfx]) }}",
dataType : "json",
type : "POST",
data : { _token: "{{csrf_token()}}" }
},
columns : [
{ data : "brand" },
{ data : "corporate" },
{ data : "num_of_company" },
{ data : "primary" },
{ data : "secondary" },
{ data : "status" },
{ data : "action",
orderable : false,
className : "text-center",
},
],
});
$('#brandDataLength').on('change', function () {
brandmanage.page.len( $(this).val() ).draw();
});
$('#searchBrand').on('keyup', function () {
brandmanage.search( this.value ).draw();
});
What do I do so that when I have moved pages, the search results can be reset?
If you change stateSave to false, then dataTables will not remember the selected filters etc. Thereby the search results will be reset when you reload the page.

How to add link with href calling javascript function with parameter in Jquery datatables?

I want to call editEmployee / deleteEmployee function from datatable column Edit / Delete Link With Parameter empId value.
How can i pass empId column value in editEmployee / deleteEmployee function called from Edit And Delete links.
Below is my javascript code :
table = $('#employeesTable').DataTable(
{
"sAjaxSource" : "/SpringDemo/employees",
"sAjaxDataProp" : "",
"order" : [ [ 0, "asc" ] ],
"aoColumns" : [
{
"className": "dt-center",
"sClass" : "center",
"mData" : "empId"
},
{
"orderable": false,
data: null,
className: "dt-center",
defaultContent: ''
} ,
{
"orderable": false,
data: null,
className: "dt-center",
defaultContent: ''
} ]
})
table = $('#employeesTable').DataTable(
{
"sAjaxSource" : "/SpringDemo/employees",
"sAjaxDataProp" : "",
"order" : [ [ 0, "asc" ] ],
"aoColumns" : [
{
"className": "dt-center",
"sClass" : "center",
"mData" : "empId"
},
{
"orderable": false,
data: null,
className: "dt-center",
defaultContent: '<a data-emp_id="[add emp id value here]" class="glyphicon glyphicon-pencil text-primary edit-link"></a>'
} ,
{
"orderable": false,
data: null,
className: "dt-center",
defaultContent: '<a data-emp_id="[add emp id value here]" class="glyphicon glyphicon-remove text-danger delete-link"></a>'
} ]
})
$('.edit-link').on('click', function () {
var empid= $(this).data('emp_id')
window.location.href="edit url ";
});
$('.delete-link').on('click', function () {
var empid= $(this).data('emp_id')
window.location.href="delete url ";
});
Basically You need to have onclick events for each based on the class.. then fetch the empID stored in the data-emp_id attribute of the button thats been clicked and then redirect appropriately
Thanks All For Comments.
I have solved issue by storing id in hidden input and accessing it in edit like this.
$(document).on('click', '#employeesTable tr', function(e) {
var row_object = table.row(this).data();
$("#hdnID").val(row_object.empId);
});
function editEmployee() {
$.ajax({
url : 'edit/' + $("#hdnID").val(),
type : 'GET',
success : function(result) {
// Do something with the result
}
});
}

add 14 days to visit date

How Can I Add plus 14days into the current visit date of my tables
it tried it this code but it show many numbers lol
------------- HERES MY CODE --------------------
//TABLE SUPERVISORY LIST
table_supervisory_list : function (id,data){
$(id).DataTable({
responsive: true,
data : data,
columnDefs:[
{
"targets":[0],
"data" : data,
"render": function (x){
return `
<button onclick="open_patient_chart(`+`'`+x.vnote_mrno+`'`+`);" type="button" class="btn btn-primary btn-minier btn-round">
<i class="fa fa-sign-in-alt"></i> `+x.vnote_mrno+`
</button>
`;
}
},
{
"targets":[1],
"data" : data,
"render": function (x){
return x.patient_lastname +' '+ x.patient_firstname +' '+ x.patient_middlename;
}
},
{
"targets":[3],
"data" : data,
"render": function (x){
return x.vnote_visitdate + moment(x.vnote_visitdate).add(7,"days");
}
},
],
columns : [
{ data : null, sTitle : 'Options' },
{ data : null, sTitle : 'Name' },
{ data : 'vnote_visitdate', sTitle : 'Last Supv done' },
{ data : null, sTitle : 'Next Supv due'},
{ data : 'vnote_formtype', sTitle : 'Action Required' },
{ data : 'vnote_enteredby', sTitle : 'Discipline' },
],
bDestroy: true
});
},
IT SHOWS 2019-04-091555344000000
That is because you're trying to append a moment object to a string.
You don't need to do that, you can simply do:
moment(x.vnote_visitdate).add(14, "days").toString();
If you want to keep the same format, you need to do something like this:
moment(x.vnote_visitdate).add(14, "days").format("YYYY-MM-DD");
Here is the documentation for the format() function.

jQuery DataTable : Browser is becoming unresponsive while downloading 16K rows to CSV

I'm using jQuery Datatable to display data. I am trying to download the data in csv format. It is working fine for around 14-15K rows of data but the browser is being unresponsive when the data is exceeding 16K rows. Here is the code:
JS Code
function createDataTable(data) {
selectedDealer = [];
allDealerData = data;
table = null;
table = $('#table_id').DataTable({
"dom" : "Bfrtip",
"data" : data,
"columns" : [ {
"data" : "id"
}, {
"data" : "dlrName"
}, {
"data" : "dlrName"
}, {
"data" : "pyramid"
}, {
"data" : ""
} ],
'columnDefs' : [ {
'targets' : 0,
'orderable' : false,
'searchable' : false,
'className' : "col-hidden",
'render' : function(data, type, full, meta) {
return data;
}
}, {
'targets' : 1,
'render' : function(data, type, full, meta) {
return data.substring(0, 11);
}
}, {
'targets' : 2,
'render' : function(data, type, full, meta) {
return data.substring(12);
}
}, {
'targets' : 4,
'width' : '0%',
'render' : function(data, type, full, meta) {
return 'Y';
}
} ],
stateSave : true,
buttons : [ {
extend : 'csv',
exportOptions : {
columns : [ 0, 1, 2, 3, 4 ]
}
} ]
});
addTableEvents();
}
Is there any solution to avoid this? Please help.

Reload Datatable with new aaData value

How to refresh the Datatable, When new Json data is sent
POST request Receives data , which is sent to LoadTable function to populate the datatable.
function initializeTable(){
$("#submitbutton").on(
'click',
function(){
$.ajax({
type : 'POST',
url : 'rest/log/events',
data : {
fromTime : $("#fromTime-filter").val(),
toTime : $("#toTime-filter").val(),
Text : $("#search-filter-input").val()
},
success : function(data) {
loadTable(data);
},
error : function(jqXHR, textStatus, errorThrown) {
showAjaxError(jqXHR, textStatus, errorThrown,
$("#error-msg"));
}
});
});
}
'data' is passed to Load function, which loads the data to a table correctly the first time.
When i submit the POST request the second time, i see New 'data' in the browser console, but the Datatable is not refreshed.
But when i Refresh the Page(datatable is cleared) and then do a new POST, new data loads normally. I want the new data to be loaded without the need to refresh the page.
function loadTable(data)
{
$('#report-table').dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
}
It looks to me like you're using DataTables v1.9. Here's how I'd do it:
function loadTable(data)
{
var table = $('#report-table');
if ( ! $.fn.DataTable.fnIsDataTable( table[0] ) ) {
table.dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
} else {
table.dataTable().fnUpdate(data);
}
}
Another option:
function loadTable(data)
{
var table = $('#report-table');
if ( ! $.fn.DataTable.fnIsDataTable( table[0] ) ) {
table.dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
} else {
table.dataTable().fnDestroy();
loadTable(data);
}
}

Categories

Resources