jquery data table action button - javascript

Can anyone help me about the best approach to add action button like edit, delete in each row in jquery data table?
I had gone through some links but didn't find a solution.
$(document).ready(function () {
$.ajax({
url: '#Url.Action("GetStudentGridData", "UserManagement")',
type: "GET",
dataType: 'json',
success: function (data) {
$('#student-datatable').DataTable({
data: data,
aoColumns: [
{ mData: "FirstName" },
{ mData: "Class" },
{ mData: "Roll" },
{ mData: "PresentAddress" },
{ mData: "BloodGroup" },
{ mData: "RegisterDate" },
{
mRender: function (data, type, full) {
return 'Edit';
}
}
]
});
},
error: function () {
alert("An error has occured!!!");
}
});
});
Here is the js code that I used to render data table. Each row has a student details and in my return 'data' object I had studentID property. I want to fetch data using that studentID when user click Edit button in a row.
Kindly help me about how to render edit and delete button and also how to handle them.
Solution :
I have tried a new approach. Instead of rendering column using datatable property I have added button in html
<table id="student-datatable" class="table table-striped table-bordered table-hover table-highlight table-checkable" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>Roll</th>
<th>PresentAddress</th>
<th>Blood Group</th>
<th>Register Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#{
foreach (var cl in Model)
{
<tr>
<td>#cl.FirstName #cl.LastName</td>
<td>#cl.Class</td>
<td>#cl.Roll</td>
<td>#cl.PresentAddress</td>
<td>#cl.BloodGroup</td>
<td>#cl.RegisterDate</td>
<td>
<div >
<button type="button" class="btn btn-default edit-student-btn" data-student-id="#cl.StudentID"><i class="fa fa-edit"></i></button>
<button type="button" class="btn btn-default"><i class="fa fa-trash"></i></button>
</div>
</td>
</tr>
}
}
</tbody>
Then I just call the jquery datatable method.
$(document).ready(function () {
$('#student-datatable').DataTable();
});
This give me nice output:

In this case, you have to use event delegation for elements added dynamically.
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
You should bind click event handler using .on() method.
$(document).on('click','.editUser',function(){
var studentID=$(this).closest('tr').find('td').eq(6).html();
});

Related

enable edit/delete in Datatables

I have a web app with cloud firestore as my backend. I used DataTable to export data from cloud firestore and display on the webpage, and the table looks like this:
Table
The code to load "orders" collection from cloud firestore and append to DataTables is:
var dataTable;
db.collection("orders").orderBy('timestamp', 'desc')
.get()
.then(function (querySnapshot) {
if (querySnapshot.size) {
var firestore_source = [];
querySnapshot.forEach(function (data) {
var obj = data.data();
obj.id = data.id;
firestore_source.push(obj);
});
//console.log('data:', firestore_source);
dataTable.clear();
dataTable.rows.add(firestore_source);
dataTable.order([0, 'desc']).draw();
}
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
$(document).ready(function () {
dataTable = $('#example').DataTable({
columns: [
{ data: 'Name' },
{ data: "Date" },
{ data: "Ins" },
{ data: "Phone" },
{ data: "Item" },
{ data: "Price"},
{ data: "Commision"},
{ data: "Revenue"},
{
data: null,
className: "center",
defaultContent: 'Edit / Delete'
}
],
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
});
$('#example').on('click', 'a.editor_remove', function (e) {
e.preventDefault();
console.log("delete clicked");
console.log($(this).closest('tr'));
// what I should do here?
} );
});
And datatables in HTML:
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Customer</th>
<th>Order Date</th>
<th>Instagram</th>
<th>Phone</th>
<th>Item</th>
<th>Price $</th>
<th>Commission</th>
<th>Earnings $</th>
<th>Edit / Delete</th>
</tr>
</thead>
</table>
Currently, the entire data within "orders" collection is loaded and obviously there are no features like editing and deleting data in each row.
So, I am stuck here that I have no idea how to identify each row in my table when clicking the edit/delete buttons on that row, so that I can use it as parameters to query cloud firestore?
I saw that there is built in tool Editor, but I am looking for native methods.
Regarding datatable API, You can get the clicked/selected row's data by this code which means you can get identity to edit or remove the selected row.
$('#example tbody').on('click', 'a.editor_remove', function () {
let row = dataTable.api().row($(this).closest("tr")).data();
console.log(row);
});

How to create delete button in Api jQuery DataTables?

How do I add the delete button using the jQuery DataTables api?
I was able to install the Datatable, but I can not implement the methods.
Can someone help me ?
https://github.com/yajra/laravel-datatables#jquery-datatables-api-for-laravel-45
 
this is my controller
public function getIndex()
{
return view('usuarios');
}
public function anyData()
{
return datatables()->eloquent(mytable::query())->make(true);
}
this is my blade.php
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>data_1</th>
<th>data_2</th>
<th>data_3/th>
<th>data_4</th>
<th>data_5</th>
<th>data_6</th>
<th>data_7</th>
<th>data_8</th>
</tr>
</thead>
</div>
this is my ajax
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'localhost/anyData',
columns : [
{data: 'data_1'},
{data: 'data_2'},
{data: 'data_3'},
{data: 'data_4'},
{data: 'data_5'},
{data: 'data_6'},
{data: 'data_7'},
{data: 'data_8'}
]
});
});
</script>
The DataTables documentation shows an example on how to delete a row by clicking on an icon inside de row.
Also it seems like the <table> element is not properly closed.

Script section works only in one view

I have a huge project in C# MVC. In one of the views, in index.cshtml, I have a code like this:
#model IEnumerable<Library.Models.Customer>
#{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Klienci</h2>
<p>
#Html.ActionLink("Nowy klient", "New", "Customers", null, new { #class = "btn btn-primary" })
</p>
<table id ="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Klient</th>
<th>Typ Czlonkostwa</th>
<th>Usun</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section scripts
{
<script>
$(document).ready(function () {
var table = $("#customers").DataTable({
ajax: {
url: "/api/customers",
dataSrc: ""
},
columns: [
{
data: "Name",
render: function(data, type, customer) {
return "<a href='/customers/edit/" + customer.Id + "'>" + customer.Name + "</a>";
}
},
{
data: "MembershipType.Name"
},
{
data: "Id",
render: function(data) {
return "<button class='btn-link js-delete' data-customer-id=" + data + ">Delete</button>";
}
}
]
});
$("#customers").on("click", ".js-delete",
function () {
var button = $(this);
if (confirm("Na pewno chcesz usunac?")) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "DELETE",
success: function () {
//datatable methods - row, remove and draw
table.row(button.parents("tr")).remove().draw();
}
});
}
});
});
</script>
}
It works like a charm. But in another view, I have the code like this:
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Ksiazka</th>
<th>Gatunek</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach (var book in Model)
{
<tr>
<td>#Html.ActionLink(book.Name, "Edit", "Books", new { id = book.Id }, null)</td>
<td>#book.Genre.Name</td>
<td>
<button class="btn-link" js-delete>Delete</button>
</td>
</tr>
}
</tbody>
#section scripts
{
<script>
$(document).ready(function() {
$("#customers .js-delete").on("click",
function() {
confirm("Sure?");
});
});
</script>
}
and it doesn't work. I mean, it compiles without any errors or warnings, but when I click Delete button nothing happens (should pop up confirm box).
What am I doing wrong?
If needed, I can provide whole code from these both views.
.js-delete means that "js-delete" is assumed to be a css class, while in the html it is an attribute. To search for elements with a particular attribute, you need "has attribute" selector:
$("#customers [js-delete]")

How to loop inside datatable columns declaration?

I have the below datatable declaration and want to display images depend on some column value (team_members). How can I declare the for loop inside columns declaration? i want this result:
var datatableVariable = $('#projects-progress').DataTable({
data: data,
columns: [
{ 'data': 'project_name' },
{ 'data': 'team_members_value' }, // to be hidden
{
//I want loop here depend on the number of team_members_value (second column above)
mRender: function (o) { return '<img src="images/img.jpg" class="avatar" alt="Avatar">';
},
/* EDIT Delete */
{
mRender: function (o) { return '<i class="fa fa-folder"></i> View <i class="fa fa-pencil"></i> Edit <i class="fa fa-trash-o"></i> Delete '; }
},
]
});
<table id="projects-progress" class="table table-striped projects">
<thead>
<tr>
<th>Project Name</th>
<th>Team Members</th>
<th>Actions</th>
</tr>
</thead>
</table>
You can use parameter render in column declaration.
{
"data": "team_members_value",
"render": function (data, type, full, meta) {
var markup = '';
for (var i = 0; i < data; i++) {
markup +='<img src="images/img.jpg" class="avatar" alt="Avatar">'
});
return markup ;
}
}
You need to do something like this:
Add render callback.
Proceed your team_members_value data to render needed markup, save it and return.

Cannot set class for row when check box clicked

I want to set a css style to the row where checkbox is clicked but am unable to do so. The code is as follows. The code for checkbox click works fine for both the select all and individual check box. I want to get the Request ID for the selected rows and send them to the database via JSON object by post method to a php script.
Possibly the row is not getting selected.
HTML:
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" name= "check_all" id="check_all"/></th>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
</table>
javascript
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID'},
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": "RequestID",
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" class="checkBoxClass" name= "check_id[]" data-id="'+data+'" />';
},
}]
});
$("#check_all").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked",false);
$('#mytable').row(this).removeClass('row_selected');
}
$('#mytable').row(this).addClass('row_selected');
});
CAUSE
There are some issues with your code:
You attach event handler directly but with jQuery DataTables only current page elements exist in DOM. Use delegated event handler instead.
You need to access row node by using $(this).closest('tr'), not $('#mytable').row(this)
Conditional statement was missing else part.
SOLUTION
Use the code below to attach delegated event handler to all checkboxes.
$("#mytable").on('change', '.checkBoxClass', function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked", false);
$(this).closest('tr').removeClass('row_selected');
} else {
$(this).closest('tr').addClass('row_selected');
}
});

Categories