Table Header is getting invisible - javascript

The table loads ok, but after load the header "View" all the others headers name came to be invisible
My Table Code:
const initTable = () => {
$("#results-table").empty();
emailReportTable = $('#results-table').DataTable({
'processing': true,
'pageLength': 150,
'data': searchResults,
'columns': [
{
'data': 'From', render: (url, type, result) => result.From
},
{
'data': 'To', render: (url, type, result) => result.To
},
{
'data': 'Cc', render: (url, type, result) => result.Cc
},
{
'data': 'Bcc', render: (url, type, result) => result.Bcc
},
{
'data': 'Subject', render: (url, type, result) => result.Subject
},
{
'data': 'Date Sent', render: (url, type, result) => moment(result.DateSent).format('DD/MM/YYYY')
},
{
'data': 'Status', render: (url, type, result) => result.Status
},
{
'data': 'View', render: (url, type, result) => "<tr class='alerta" + 1 + "'><td class='hidden-xs'> <button type='button' class='btn btn-xs btn-danger' >Alert</button> <a href='#' data-toggle='tooltip' title='Create task'><i class='fa fa-edit' data-toggle='modal' data-target='#Modal-" + 1 + "task'></i></a></td>"
},
],
'language': {
'zeroRecords': 'No results found'
}
});
}
I need all headers continue visible, when i remove the buttons TR we works fine.

Related

how to add a href route with parameter in datatable

here is i have a datatable based table i have fetched a data from database and displayed using datatable but in this datatable i went to redirect to show for each row of datatable so how to add a route for show with parameter 1d for each row thanks and waiting a positive response!
here is my code
<script>
$(function() {
$("#start_date").datepicker({
"dateFormat": "yy-mm-dd"
});
$("#end_date").datepicker({
"dateFormat": "yy-mm-dd"
});
});
// Fetch records
function fetch(start_date, end_date,zone_id,status_id,sector_id) {
$.ajax({
url: "{{ route('ProjectFilterdate/records') }}",
type: "GEt",
data: {
start_date: start_date,
end_date: end_date,
zone_id:zone_id,
status_id:status_id,
sector_id:sector_id
},
dataType: "json",
success: function(data) {
// Datatables
var i = 1;
$('#records').DataTable({
"data": data.ptojects,
// buttons
"dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
"buttons": [
'copy','excel', 'pdf', 'print'
],
// responsive
"responsive": true,
"columns": [{
"data": "id",
"render": function(data, type, row, meta) {
return i++;
}
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "proposal_date"
},
{
"data": "proposal_value"
},
{
"data": "contractor"
},
{
"data": "subcontractor"
},
{
render: function ( data, type, row) {
return 'test';
}
},
]
});
}
});
}
i am trying to make an a href route but i don't know how to add an id parameter
here is the link i am trying
{
render: function ( data, type, row) {
return 'test';
}
the place of 1 must be replaced by id for each row
This is how i did t :
return DataTables::of($data)->addIndexColumn()
->addColumn('project', function ($test) {
return $test->project->title;
})
->addColumn('action', function ($test) {
$result = $test->active ? 'btn-success' : 'btn-danger';
return '<a href="' . route('projectDetail', [
'id' => $test->id
]) . '">detail </a>
';
})
->rawColumns([
'action'
])
->make(true);
}

Issue with Datatable and JSON calculation

I am using datatable, loading data from ajax and preforming operation with javacript.
var table = $('#example').DataTable({
"ajax": {
"url": apiurl,
"type": 'GET',
"datatype": 'json'
},
// data: dataSet,
columns: [
{ title: "Item Key", data: "itemKey" },
{ title: "Description", data: "description" },
{ title: "Pounds", data: "pound" },
{
title: "Current Cost", data: function (data, type, row) {
return '<input type="number" class ="price-input" value="' + data.cost + '" style="background-color:lightgoldenrodyellow;">';
}
},
{ title: "Current Cost", data: "cost" },
{ title: "Unit", data: "unit" },
{
title: "Quantity", data: "quantity"
},
{
title: "Total", data: function (data, type, row) {
return data.cost * data.quantity;
}
},
{
title: "New Total", "data": "total",
"render": function (data, type, row) {
return "$" + data;
}
}
],
});
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
var table = $('#example').DataTable();
$.each(table, function (i, r) {
r.total = calcTotal(r.qty, r.price);
});
$("#example").on("change", ".price-input", function (event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(6)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(8).get(0));
total.data(calcTotal(qty, price)).draw();
});
'''
My problem is in the last column, when the datatable loads, value appear as undefined, when I change the value in textbox I am getting the right result and number How Can I able to see right number when Datatable loads? Please guide me

Get value from Kendo UI grid filter and autofill

I have a an MVC web app, and in one of my views I have a Kendo UI grid:
#(Html.Kendo().Grid<Custodias.Models.ProjectMessageRecipientsModel>()
.Name("grid")
.Columns(columns =>
{
columns.ForeignKey(p => p.ProjectID_FK, (System.Collections.IEnumerable)ViewBag.ProjectList, "Value", "Text").Title("Project").Width(150).Filterable(filterable => filterable.Cell(e => e.Operator("eq").SuggestionOperator(FilterType.Contains).ShowOperators(false))); ;
columns.ForeignKey(p => p.ServiceUserID_FK, (System.Collections.IEnumerable)ViewBag.ServiceUserList, "Value", "Text").Title("Service User").Width(150).Filterable(filterable => filterable.Cell(e => e.Operator("eq").SuggestionOperator(FilterType.Contains).ShowOperators(false)));
columns.ForeignKey(p => p.ProcessKeyID_FK, (System.Collections.IEnumerable)ViewBag.ProcessKeyList, "Value", "Text").Title("Process Key").Width(150).Filterable(false);
columns.ForeignKey(p => p.ContactID_FK, (System.Collections.IEnumerable)ViewBag.ContactList, "Value", "Text").Title("HideContact").Width(150).Filterable(false);
columns.Bound(p => p.ContactName).Title("Contact").Width(200).Filterable(false).Hidden();
columns.Command(command => { command.Edit(); }).Width(90);
columns.Command(command => { command.Destroy(); }).Width(90);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp).Window(w => w.Title("Edit Project Message Recipients").Width(500))).Events(e => e.Edit("onPopOpen"))
.Pageable()
.Resizable(resize => resize.Columns(true))
.Sortable()
.Scrollable()
.Filterable(ftb => ftb
.Mode(GridFilterMode.Row)
.Extra(false)
)
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events =>
{
events.RequestEnd("onRequestEnd");
})
.Model(model => model.Id(p => p.ProjectMessageRecipientID_PK))
.Create(update => update.Action("CreateProjectMessageRecipients", "ProjectMessageRecipients"))
.Read(read => read.Action("BindProjectMessageRecipientsModel", "ProjectMessageRecipients"))
.Update(update => update.Action("UpdateProjectMessageRecipients", "ProjectMessageRecipients"))
.Destroy(update => update.Action("DeleteProjectMessageRecipients", "ProjectMessageRecipients"))
)
)
What I'd like to be able to do, is when someone uses the search filter in that first column ("Project") and then goes to add a new record, I want the value from that search filter to be automatically filled into the dropdown list in the "Add New Record" pop-up:
Is that possible?
You can handle it within the beforeEdit event. It receives the model as the parameter, with it you can overwrite the properties you like. Next, you can get the dataSource's filters and find the value you need to set in the model. E.g.:
var grid = $("#grid").data("kendoGrid");
grid.bind("beforeEdit", (e) => {
let filter = e.sender.dataSource.filter().filters.find(filter => filter.field === 'ProductName');
e.model.ProductName = filter.value;
});
Demo(in pure JavaScript):
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/editing-popup">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.1.224/styles/kendo.default-v2.min.css" />
<script src="https://kendo.cdn.telerik.com/2021.1.224/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.1.224/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
filterable: {
mode: "row"
},
columns: [
{ field:"ProductName", title: "Product Name",
filterable: {
cell: {
operator: "contains",
suggestionOperator: "contains"
}
}
},
{ field: "UnitPrice", title:"Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px", editor: customBoolEditor },
{ command: ["edit", "destroy"], title: " ", width: "120px" }],
editable: "popup",
beforeEdit: (e) => {
let filter = e.sender.dataSource.filter().filters.find(filter => filter.field === 'ProductName');
e.model.ProductName = filter.value;
}
});
});
function customBoolEditor(container, options) {
$('<input class="k-checkbox" type="checkbox" name="Discontinued" data-type="boolean" data-bind="checked:Discontinued">').appendTo(container);
}
</script>
</div>
</body>
</html>
Dojo
To get apply filters of a grid with => grid.dataSource.filter()
To check grid filter length with below
var grid = $("#gridID").data("kendoGrid");
if(grid.dataSource.filter()==null){
console.log(0);
}
else{
grid.dataSource.filter().filters.length;
}

jquery server-side datatable not wroking properly

I added the server side jQuery data-table, Data from back-end coming correctly for all pagination, sorting etc. and also bind the data first time, but second time not replacing the content of data-table with new data.
Here is my JQuery code:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
"columns": [
{
"data": "tblRow",
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{ data: "cust_name" },
{ data: "status" },
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
data: ".account_id",
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});
Please Help. Thank you in advance.
Try with "columnDefs"(datatables example) prop instead "columns" like:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
// HERE CHANGE
"columnDefs": [
{
// HERE CHANGE ( COLUMN INDEX)
"targets": 0,
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{
"targets": 3,
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
"targets": 4,
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
"targets": 5,
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});

csrf token set as post parameter while deleting action in Jtable (Jquery )

Hi i'm trying to add csrf token in post while deleting record in jtable its not working but listAction & updateAction is working fine.
My Code snippets :-
$(document).ready(function () {
$('#main-content').jtable({
title: ' Data',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
actions: {
listAction:"${pageContext.request.contextPath}/mycontroller/all" ,
// createAction:"${pageContext.request.contextPath}/mycontroller/create",
updateAction:"${pageContext.request.contextPath}/mycontroller/edit",
deleteAction:"${pageContext.request.contextPath}/mycontroller/delete"
},
fields: {
code: {
title:'Code',
width: '25%',
key: true,
edit:true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="code" value="' + data.value + '"/>';
}
},
},
name: {
title: 'Name',
width: '25%',
create:true,
edit:true
},
craetedTs: {
title: 'Created',
width: '25%',
edit:false
},
modifiedTs: {
title: 'mdate',
width: '25%',
edit:true,
input: function (data) {
if (data.value) {
mdate='';
var date = new Date();
var options = {
year: "numeric", month: "2-digit",
day: "2-digit", hour: "2-digit", minute: "2-digit" ,second:"2-digit"
};
today=date.toLocaleTimeString("en-us", options);
today=today.replace(',', '');
return '<input type="text" readonly class="jtable-input-readonly" name="modifiedTs" value="' + today + '"/>';
}
}
},
_csrf: {
visibility: 'hidden',
edit:true,
input: function (data) {
return '<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />';
}
}
}
});
$('#main-content').jtable('load',{'${_csrf.parameterName}' : '${_csrf.token}'});
//Delete selected
$('#DeactiveID').button().click(function () {
var $selectedRows = $('#main-content').jtable('selectedRows');
$('#main-content').jtable('deleteRows', $selectedRows);
});
});
Even i tried for deleting code bellow:-
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
data: '${_csrf.parameterName}' + "=" +'${_csrf.token}' ,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
But when i checked delete action url the entire method was reflecting
Add meta elements to the page you are invoking the ajax method from
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
And make this change to your deleteAction
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
beforeSend: function (request)
{
request.setRequestHeader(header, token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
If somebody is still wondering, Lalit got me going in the right direction, but my final solution is this:
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
This solves the issue with passing csrf, or any additional data, for that matter, in jTable AJAX delete call. As for the other cases. Putting this right after you include the jTable js foxes the initial load:
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
And then there is this hidden field to add to the field list:
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
Here is my code as a full example:
<!-- Include jTable script file. -->
<script src="{{site.uri.public}}/jtable/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
var csrf_token = $('meta[name=csrf_token]').attr("content");
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var csrf_token = $('meta[name=csrf_token]').attr("content");
$("#PrizesTableContainer").jtable({
title: 'Prizes',
actions: {
listAction: 'prizes/get',
createAction: 'prizes/create',
updateAction: 'prizes/update',
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
id: {
key: true,
list: false
},
machine_name: {
title: 'Machine name',
width: '10%'
},
reel1: {
title: 'Reel1',
width: '15%'
},
reel2: {
title: 'Reel2',
width: '15%'
},
reel3: {
title: 'Reel3',
width: '15%'
},
payout_credits: {
title: 'Payout credits',
width: '15%'
},
payout_winnings: {
title: 'Payout winnings',
width: '15%'
},
probability: {
title: 'Probability',
width: '15%'
},
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
}
});
$("#PrizesTableContainer").jtable('load');
});
</script>

Categories