How to show edit delete button in one column? - javascript

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

Related

Is there another way to pass an object to a function?

I have a datatable which is requesting data from an API. I am getting an object called full which has all the variables from the database. I can access integers without a problem and pass them from a function upon a button click but a string is bringing an error saying Uncaught SyntaxError: missing ) after argument
<script>
$(document).ready(function () {
$("#datatable").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
"url": '#TempData["api"]api/Versioning/Review',
headers: {
'Authorization': 'Bearer #HttpContextAccessor.HttpContext.Session.GetString("token")'
},
"type": "GET",
},
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
{ "data": "name", "name": "Name", "autoWidth": true },
{ "data": "name", "name": "Name", "autoWidth": true },
{
data: "created_at",
"render": function (value) {
if (value === null) return "";
return moment(value).format('DD/MM/YYYY');
}
},
{
"render": function (data, type, full, meta) {
return '<button onclick="changes('+full.changes+')" class="btn btn-info"><i class="fas fa-info-circle"></i> Changes</button>';
}
},
{
"render": function (data, type, full, meta) {
return "<button id='remove' onclick='approve("+full+")' class='btn btn-success'><i class='fas fa-check-circle'></i> Accept Version</button>";
}
},
{
"render": function (data, type, full, meta) {
return "<button id='deny' onclick='deny(" + full.id + ")' class='btn btn-danger'><i class='fas fa-minus-circle'></i> " + full.changes + "</button>";
}
},
]
});
});
<script/>
Above i am requesting the data and i cant received the full.changes on my function and i cant even log it. But when am passing in an ID its working and i can log it. I also tried passing in the full object full and then accessing it in my function like full.changes but still its not working. Below is my function
<script>
function changes(changes) {
console.log(changes)
}
</script>
Basically what i want is to log the variable called changes which is in the full object but so far no success. Anyone know how i can pass it?
You should produce quotes around a string literal in your HTML. They are missing.
So replace this:
return '<button onclick="changes('+full.changes+')" class="btn btn-info"><i class="fas fa-info-circle"></i> Changes</button>';
With
return '<button onclick="changes(\''+full.changes+'\')" class="btn btn-info"><i class="fas fa-info-circle"></i> Changes</button>';
Do similar things (with the appropriate quote and escaping) in the other cases.

ASP.NET MVC Add chebox filtering

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>

DataTables add tag to column based on another attribute's value

I am trying to get the <span> tag into the "salesStatusName" column cell that already has some data in it. The tag should be placed in there when the value of the last column "completelyDelivered" is true. However, I also don't want "completelyDelivered" to even be a column in the table, so I assume I somehow need to access the value of "completelyDelivered" attribute in the received JSON.
How it looks now:
https://i.imgur.com/S171i2o.png circle in a separate column
How I want it to look:
https://i.imgur.com/74nCnGu.png circle within Status Name column
I looked around and there are very similar questions, but I was unable to implement any solution.
DataTables instantiation code:
Note that I use AJAX and get JSON code returned
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
"columns": [
{ "data": "salesOrderNumber" },
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": "salesStatusName" },
{ "data": "completelyDelivered" }
],
"columnDefs": [
{
"targets": 0, //salesOrderNumber col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/Get?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 7, //completelyDelivered col
"render": function (data) {
if (String(data) == "true") {
return '<span class="SalesOrderDelivered">⬤</span>';
}
return "";
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});
I've done some research and figured it out.
Basically, if you write { "data": null }, as a definition for a column, you gain access to all properties of that row. So, in "render": function(data) function, write data["propertyName"] to get the value.
Code:
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
{"data": "salesOrderNumber",},
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": null, },//this is Sales Status column.
//"data: null" accesses all JSON data. We need this so that in "columnDefs" section
//we can use the values of both "completelyDelivered" and "salesStatusName" properties.
],
"columnDefs": [
{
"targets": 0, //button col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/GetShipments?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 6, //Sales Status col.
"render": function (data) { //This is where we can use values of "completelyDelivered" and "salesStatusName" JSON properties.
if (String(data["completelyDelivered"]) == "true") {
return (String(data["salesStatusName"]) + '<span class="AllDelivered"> ⬤</span>');
} else {
return String(data["salesStatusName"]);
}
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});

How can I get the current page from within the $().DataTable() function?

I am working on an ASP.Net Core 2.1 MVC web application and I am using DataTables.Net datatable v1.10.19 for my lists.
I am creating master/detail drill downs where the first list (DataTable) of job activity provides a link on each row to the respective detail record. I am using pagination as well.
On the detail record, I want to have a breadcrumb that takes me back to the job activity list, and to the correct page number where I was at then I clicked on the detail link.
What I am doing is passing the query properties I am using on the Job Activity DataTable as query string parameters to the detail page so I can correctly populate the breadcrumb URL back to the job activity page.
I can see on the DataTable.Net API reference that I can use page.info() from the API to get the current page using something like this;
var table = $('#example').DataTable();
var info = table.page.info();
$('#tableInfo').html(
'Currently showing page '+(info.page+1)+' of '+info.pages+' pages.'
);
The problem is that I initialize the DataTable as part of the table setup and in the body of that function is where I am populating the link data for the detail page. I can't seem to do two .DataTable() calls, such as doing the call to the DataTable function to get the page info to initialize a pageNumber variable and then call the main .DataTable function as it causes the init of the main DataTable function to fail.
So, I need a way to get the current page from within the main .Datatable() function, if possible.
Here is my main DataTable() function;
jQuery(document).ready(function($) {
//Get the Timezone offset between local time and UTC
var d = new Date();
var m = d.getTimezoneOffset();
var minutesToOffset = parseInt(m, 10);
var companyId = $('#company-filter').val();
var siteId = $('#site-filter').val();
var aging = $('#aging-filter').val();
console.log(`companyId: [${companyId}], siteId: [${siteId}], Aging Days: [${aging}]`);
var table = $("#ssflist").DataTable({
//"dom": "lrtip",
"initComplete": function() {
$('#spinner1').hide();
$('#spinner2').hide();
},
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"order": [[6, "desc"]],
"ajax": {
"url": `/JobActivity/LoadData?companyId=${companyId}&siteId=${siteId}&agingDays=${aging}`,
"type": "POST",
"datatype": "json"
},
"oLanguage": {
"sSearch": "Filter"
},
"columnDefs": [
{ "orderable": false, "targets": [9, 10] },
{ "className": "text-center", "targets": [0, 9, 10] },
{
"targets": [6, 7],
"render": function(data) {
if (data != null) {
return moment(data).subtract(minutesToOffset, 'minutes').format('M/D/YYYY h:mm a');
}
}
}
],
"columns": [
{
"render": function(data, type, full, meta) {
if (full.ManifestStatus === 0) {
return '<i class="far fa-clock text-primary" title="Not started"></i>';
} else if (full.ManifestStatus === 1) {
return '<i class="fas fa-sync-alt text-primary" title="Pending"></i>';
} else if (full.ManifestStatus === 2) {
return '<i class="far fa-file-alt text-primary" title="Manifested"></i>';
} else if (full.ManifestStatus === 3) {
return '<i class="far fa-times-circle text-danger" title="Failed"></i>';
} else if (full.ManifestStatus === 4) {
return '<i class="far fa-check-circle text-primary" title="Uploaded"></i>';
} else return '<i class="far fa-question-circle text-primary" title="Unknown status"></i>';
},
"name": "ManifestStatus"
},
{
"render": function(data, type, full, meta) {
if (type === 'display' && data != null) {
data =
`<a href="/shippingServicesFileDetail/detail?id=${full.Id
}&returnTitle=Job Activity List&companyId=${companyId}&siteId=${siteId}&agingDays=${
aging}">
<button type="button" class="btn btn-outline-primary btn-sm">` +
data +
`</button></a>`;
}
return data;
},
"data": "Id",
"name": "Id"
},
{ "data": "TransactionId", "name": "TransactionId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "ReferenceId", "name": "ReferenceId", "autoWidth": true, "defaultContent": "" },
{ "data": "CreatedDate", "name": "CreatedDate", "autoWidth": true, "defaultContent": "" },
{ "data": "UploadDate", "name": "UploadDate", "autoWidth": true, "defaultContent": "" },
{ "data": "Environment", "name": "Environment", "autoWidth": true, "defaultContent": "" },
{
"render": function(data, type, full, meta) {
data = full.H1RecordCount + full.D1RecordCount + full.C1RecordCount;
return data;
},
"name": "Count"
},
{
"render": function(data, type, full, meta) {
if (full.AzureFileUrl != null) {
data =
`<a href="/JobActivity/getManifest?azureFileUrl=${full.AzureFileUrl
}&azureFileName=${full.AzureFileName}">
<i class="far fa-arrow-alt-circle-down text-primary" title="Download Manifest"></a>`;
return data;
} else {
return null;
}
},
"name": "AzureFileUrl"
}
],
// 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);
},
});
$('#companyId').on('change',
function() {
table.search(this.text).draw();
});
});
The relevant link code is...
data = `<a href="/shippingServicesFileDetail/detail?id=${full.Id
}&returnTitle=Job Activity
List&companyId=${companyId}&siteId=${siteId}&agingDays=${
aging}">
I want to add a parameter to this link that represents the current page of the Datatable so that I can pass it back in the breadcrumb link on the detail page and have the datatable go to the correct page.
So I need a way to get the current page from within the
var table = $("#ssflist").DataTable({
function itself so I can pass that value in the link to the detail page.
Is there a property or method from within the Datatable function that will get me the current page value?

Add Empty Row(For Insert) in jquery Datatable (Not Editor) in bottom after data

my question is not how to put the empty row its why the empty row appear as first row
function BindCenterTable(ID,val) {
var strSearchLang = " ";
txtCenetrTotal.value = val;
if (lang == 'en-US') {
strSearchLang = " Search ";
}
$.ajax({
type: "Post",
url: 'Query.asmx/FillSubTransCenters',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{SubTransID: ' + ID + '}',
success: function (data) {
if (typeof CenterTable != 'undefined')
CenterTable.destroy();
CenterTable = $('#tableCenters').DataTable({
"aaData": JSON.parse(data.d),
"bFilter": true,
"bInfo": false,
"lengthChange": false,
"oLanguage": {
"sSearch": strSearchLang
},
"paging": false,
"columns": [
{ "data": "id" }, { "data": "Center_No" },
{ "data": "CenterName" }, { "data": "Value" },
{ "data": "Val_Percent" }
],
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
}, {
"targets": 5,
"data": null,
"defaultContent":
' <button class="btn btnEdit" type="button"> <i class="fa fa-pencil " style="font-size:20px"></i> </button> <button class="btn btnDelete" type="button"> <i class="fa fa-trash " style="font-size:20px"></i> </button>'
}
],
});
AddCenterEmptyRow();
},
error: function (err) {
// alert(err);
}
})
}
function AddCenterEmptyRow() {
var rowNode = CenterTable.row.add({
"id": "0", "Center_No": "0", "CenterName": "0",
"Value": "0", "Val_Percent": "0"
}).draw().node();
if (rowNode) {
var jqTds = $('>td', rowNode);
jqTds[0].innerHTML = '<table style="width:100%"><tr><td><input type="button" id="btnNewCenter" value="..." ></td><td><input type="text" class="twitterStyleTextbox" style="width:60px" id="txtNewCenter_No" readonly ></td></tr></table>';
jqTds[1].innerHTML = '<input type="text" class="twitterStyleTextbox" readonly id="txtNewCenterName" >';
jqTds[2].innerHTML = '<input type="number" style="width:60px" id="txtNewCenterVal" class="twitterStyleTextbox">';
jqTds[3].innerHTML = '<input type="number" style="width:60px" id="txtNewCenterPerc" class="twitterStyleTextbox">';
jqTds[4].innerHTML = '<button class="btn btnSubNewCenterSave" type="button"> <i class="fa fa-save " style="font-size:20px"></i> </button> '
}
var e = document.getElementById('txtNewCenterVal');
e.oninput = CenterValChange;
e.onpropertychange = e.oninput; // for IE8
var e = document.getElementById('txtNewCenterPerc');
e.oninput = CenterPercChange;
e.onpropertychange = e.oninput; // for IE8
//var e = document.getElementById('txtNewEchange_Rate');
//e.oninput = DebitChange;
//e.onpropertychange = e.oninput; // for IE8
}
every thing works fine but the data appear after the empty row
1-is there a way to select the order where to put the empty row
2- is there a better way for inserting an empty row
Note : i can not use the footer because it is used for summery but that code is not included
Thank you
Edit
According to the creator of Datatables answering a related question:
The row will be positioned according to the ordering applied to the
table. Where ever the table's ordering positions the row, that is
where it will appear.
My solution would be to use the sorting functionality to do this
Here is a live example of what i would do...
Hope this helps
Don't need jquery for this just put it in the footer <tfoot></tfoot> of your HTML table.

Categories