I am newbie for DataTables. I want to add button on each row for edit and delete(like below image)
I have tried with code:
Test.cfm
<table id="myDataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>UserID</th>
<th>Name</th>
<th>UserName</th>
<th>Passowrd</th>
<th>Email</th>
<th>IsActive</th>
<th>Command</th>
</tr>
</thead>
<tbody>
</tbody>
$(document).ready(function () {
var oTable = $('#myDataTable').dataTable({
// "bServerSide": true,
"sAjaxSource": "fetchUserData.cfm",
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mData": null },
{ "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
{ "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
{ "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%" },
{ "mData": "Email","sTitle": "Email" , "sWidth": "20%"},
{ "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
{
"mData": null,
"bSortable": false,
"mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
}
]
});
} );
fetchUserData.cfm
{
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
[
"2",
"arun singh",
"arun",
"arun",
"arunsingh#test.com",
"0",
""
],
[
"9",
"s s",
"sam3",
"sam3",
"ss#s.com",
"0",
""
],
[
"10",
"sameek mishra",
"sam56",
"sam",
"same#s.com",
"0",
""
],
[
"11",
"narendra kumar",
"narendra",
"nav",
"sa#sa.com",
"1",
""
],
[
"12",
"test test",
"test",
"test",
"test2#test.com",
"1",
""
]
]
}
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered.
I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype (can be ignored mostly)
full = The full data array for this row.
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
var table =$('#example').DataTable( {
data: yourdata ,
columns: [
{ data: "id" },
{ data: "name" },
{ data: "parent" },
{ data: "date" },
{data: "id" , render : function ( data, type, row, meta ) {
return type === 'display' ?
'</i>' :
data;
}},
],
}
}
take a look here... this was very helpfull to me
https://datatables.net/examples/ajax/null_data_source.html
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
I contribute with my settings for buttons: view, edit and delete.
The last column has data: null
At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
enter image description here
Take a Look.
$(document).ready(function () {
$('#datatable').DataTable({
columns: [
{ 'data': 'ID' },
{ 'data': 'AuthorName' },
{ 'data': 'TotalBook' },
{ 'data': 'DateofBirth' },
{ 'data': 'OccupationEN' },
{ 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
],
bServerSide: true,
sAjaxSource: 'EmployeeDataHandler.ashx'
});
});
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
well, i just added button in data.
For Example,
i should code like this:
$(target).DataTable().row.add(message).draw()
And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!
Related
I am using jQuery data table. I pass one id via <a href="#">. Now, i want to pass two or more id in single cell and <a href="#">.
My Code:
var table = $('table#companyTable').DataTable({
"sAjaxSource": ResultData, // "/GetcompanyList.json",
"sAjaxDataProp": "",
/// sort at column three
"order": [[ 3, "asc" ]],
"aoColumns": [
{ "mData": null },
{ "mData": "registrationType" },
{ "mData": "companyName" },
{ "mData": "emailId" },
{ "mData": "country" },
{ "mData": "district" },
{ "mData": "registrationDate" },
{ "mData": "companyId" },
{ "mData": "tendererId" },
{
"mData": "userId",
"render": function(data, type, row, meta){
if(type === 'display'){
data = 'View';
}
return data;
}
}
],
// define first column , is column zero
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}]
});
Now i need to pass userId, companyId, tendererId in one render and href link.
Just like below
data = 'View';
I have created a query table using data from json.
I am trying to combine two column values in one
but i always get undefined data when i try to combine two columns.
I am not sure what is wrong here.
not sure what is wrong here
$("#submit").click(function(){
var dataTableExample = $('#tbl_jad').DataTable();
$('#tbl_jad').show();
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample =
$('#tbl_jad').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "ID"
},
{
"mData": "Position_x0020_Number",
},
{
"mData": "Title"
}, {
"mData": "Type_x0020_of_x0020_Action"
}, {
"mData": "Series"
}]
,
"columnDefs": [
{
"render": function ( data, type, row ) {
return data +' ('+ row[0]+')';
},
"targets": 1
},
{ "visible": false, "targets": [ 0 ] }
]
});
}
});
return data +' ('+ row["ID"]+')'
where ID is the column heading or column name
How to use java script variable inside blade syntax. (getting error Use of undefined constant buttonID)
The below is the code :
var t = $("#datatable").DataTable({
"order": [[ 1, 'asc' ]],
"ajax": "questions1/get-data",
"deferRender": true,
"processing": true,
sAjaxDataProp: "",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "description" },
{ "data": "answers.[, ].name" },
{ "data": "campaigns.[, ].name" },
{ "data": "label" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
return '#can('view', $question)<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>#endcan
#can('update', $question)<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>#endcan';
}
}
],
});
Use the code below:
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
#can('view', $question)
return '<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>';
#endcan
#can('update', $question)
return '<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>';
#endcan
}
I'm using JQuery DataTable with server side processing. And I've written this code:
public List<VacationRequest> GetVacationRequestsWithProfiles(int displayStart, int displayLength, out int allDataCount, out int filteredDatacount, string searchParam = "", string searchDir = "")
{
....
switch(searchDir)
{
case "asc":
requests = requests.OrderBy(x => x.FirstName).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
case "desc":
requests = requests.OrderByDescending(x => x.FirstName).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
default:
requests = requests.OrderBy(x=>x.VacationRequestState).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
}
....
}
The problem: I need to get default (empty) search parameter to this method, when page loaded. How I may resolve this?
This is a part of JS code:
"aoColumns": [
{ "data": "ID", "visible": false, bSortable: false, bSearchable: false },
{ "data": "Name" },
{
"data": "VacationRequestStatus",
bSortable: false,
bSearchable: false,
"mRender": function (data, type, full) {
return '<div class = "' + data + '"> <span class="glyphicon glyphicon-question-sign requested-img"></span> <span class="glyphicon glyphicon-ok accept-img"> </span> <span class="glyphicon glyphicon-remove decline-img"></span> </div>';
}
},
{ "mData": "Position", bSortable: false, bSearchable: false },
{ "mData": "DateStart", bSortable: false, bSearchable: false },
{ "mData": "DateEnd", bSortable: false, bSearchable: false },
{
bSortable: false,
bSearchable: false,
data: null,
className: "center",
defaultContent: '<button class="btn btn-danger decline-button">Decline</button> <button class="btn btn-primary accept-button">Accept</button>'
}
]
because dont know where u put ajax try add this command ine the line before aoColumns
"destroy" : true,
"aoColumns": [
thats command to stop data display in datable but after search data will diplay hope solve ur problems
I am new to Datatables and trying to figure out this problem.
I have a server which oupts json in certain format(see below).I cant change that on server side.
**Note: I am using link http://www.json-generator.com/j/cftupHnpbC?indent=4 to emulate my server response just for checking.
I have 2 problems
Since My json response doesn't have aaData: thing required by dataTable, I cant seem to initiliaze it.
Even if I add aaData: by hand to json just for checking, dataTable cant count total records.How I can set that manually ?Since I cant change output from server.
JSBIN LINK:
http://live.datatables.net/dasuyaf/1/edit
HTML:
<table id="example" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
$(document).ready( function () {
var table = $('#example').dataTable({
"sAjaxSource": "http://www.json-generator.com/j/cftupHnpbC?indent=4",
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
My Server Output: (cant change this)
[
{
"text": "Some text",
"name": "somedata",
"id": "89"
},
{
"text": "Some text",
"name": "somedata",
"id": "2"
},
{
"text": "Some text",
"name": "somedata",
"id": "12"
}
]
I suppose you could just request that JSON yourself, make an object out of it and pass it to your dataTable.
var aaData;
var table;
$(document).ready( function () {
$.ajax({
url: 'http://www.json-generator.com/j/cftupHnpbC?indent=4'
}).done(function(data){
aaData = data;
table = $('#example').dataTable({
"aaData": aaData,
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
} );
I removed bServerSide - I don't think there's any way you can make use of it if you can't change your server response. Also removed sServerMethod.