How to create delete button in Api jQuery DataTables? - javascript

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.

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

Datatables json data displaying all data on one line

I am trying to setup datatables to read my json API to display data in a table. Currently it is outputting all of the object contents into one line instead of looping it like a table should be displayed.
My jsfiddle
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Blocks</th>
<th>Amount</th>
<th>Date</th>
</tr>
</thead>
</table>
JS
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://zelcash.voidr.net/api/payments",
dataSrc : ''
},
"columns" : [ {
"data" : "payments.[].blocks.[]"
}, {
"data" : "payments.[].amounts.t1XHpNtYY2N3EMDRoX9RM2hq4DWWPZSmawJ"
}, {
"data" : "payments.[].time"
}]
});
});
You need an endpoint to return only an array, because this endpoint https://zelcash.voidr.net/api/payments return some objects.
You can check the datatables documentation:
https://datatables.net/examples/data_sources/ajax in this example the ajax url is https://datatables.net/examples/ajax/data/arrays.txt and this return an array.

jquery data table action button

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

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

binding jquery datatable gives error "Requested unknown parameter '0' from the data source for row 0"

i am creating json format for jquery datatable using jquery ,
but it gives error "DataTables warning (table id = 'tblDynamicModifierItems2'): Requested unknown parameter '0' from the data source for row 0"
my Html is
<table id="tblDynamicModifierItems" class="tblDynamicModifierItems table table-hover table-nomargin dataTable table-bordered dataTable-scroller dataTable-tools">
<tbody></tbody>
</table>
my Jquery code is
var aaData = [];
var ModifierItemCode = "1";
var Description = "10 cane rum"
aaData.push({
"ModifierItemCode": ModifierItemCode,
"ModifierItem": Description,
"Delete": "Delete"
});
var oTable = $("#tblDynamicModifierItems").dataTable({
"aaData": aaData,
"aoColumns": [{ "bVisible": false }, { "sTitle": "Description" }, null],
});
oTable.fnSort([[1, 'asc']]);
can anyOne help me solve this?
You need to make the markup right. jQuery dataTables is very sensitive to that. It is important to define the headers, <th>, so dataTables have a chance to know how many columns it should expect in each row of data.
<table id="tblDynamicModifierItems" class="tblDynamicModifierItems table table-hover table-nomargin dataTable table-bordered dataTable-scroller dataTable-tools">
<thead>
<tr>
<th>ModifierItemCode</th>
<th>ModifierItem</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
Also, you must tell dataTables which part of each aaData item that should correspond to which column :
var oTable = $("#tblDynamicModifierItems").dataTable({
"aaData": aaData,
"aoColumns": [
{ mDataProp : "ModifierItemCode" },
{ mDataProp : "ModifierItem" },
{ mDataProp : "Delete" }
]
});
your code in a demo -> http://jsfiddle.net/s9Lag6mc/
Regarding your "aoColumns": [{ "bVisible": false }, { "sTitle": "Description" }, null], I am not completely sure what you are trying to do, but if you want to hide the first column, just add bVisible: false to the first aoColumns item, and so on.
As for your fnCreatedRow problem : Think about it, you are inserting an object. So instead of alert(aData[0]) (or whatever) simply
alert(aData.ModifierItemCode);
forked fiddle -> http://jsfiddle.net/0aLys2d3/

Categories