JS. Conditions in dataTable - javascript

Hi I have the following structure:
$(document).ready(function () {
$('#employee_data').dataTable({
'ajax': {
"processing": true,
"serverSide": true,
"url": 'get-data.php',
"dataType": 'json',
dataSrc: '',
},
"columns": [
{"data": "num"},
{"data": "date"},
{"data": "value"},
{"data": "max"},
{"data": "min"},
{"data": "name"}
],
});
});
How can I write conditions in the "value" column?
Example:
if (data["Num"] === '1' && (data['Value'] >= 120 || data['Value'] <= 20 || isNaN(data['Value']))) {
return ' class="class1" ';

You Can Write That Condition Like This, Here is My Code
Use The Render for return the data.
{ "data": "connected" ,
render: function ( data, type, row ) {
let html = ``;
if(data == '1'){
html = `<button type="button" class="btn btn-block btn-success btn-sm">Connected</button>`;
}
else {
html = `<button type="button" class="btn btn-block btn-danger btn-sm">Disconnected</button>`;
}
return html;
} }

Related

How to show edit delete button in one column?

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

JQuery - how to add a button to an column from the table

I want to add a button to the column Action but I cant put the value of data-activateUser= item["AspNetUserId"]. I am jusing a plugin DataTables btw.
My Table
DataSource
$.getJSON("/Account/InactiveAccounts").then(function (items) {
var item = items;
console.log(item["UserAccounts"]);
$('#inactive-accounts').DataTable({
columnDefs: [{ targets: 'no-sort', orderable: false }],
data: item["UserAccounts"],
"processing": true,
columns: [
{ data: "Username" },
{ data: "Password" },
{ data: "Email" },
{
data: function () {
return `<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser=`+ item["AspNetUserId"] +`>Activate</button>
`;
}
}
]
});
JSON Data
Please change your
data: function () {
return `<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser=`+ item["AspNetUserId"] +`>Activate</button>`;
}
to
render: function (data, type, row, meta) {
return '<button onclick="clickDeactivateUser(this)" class="btn btn-danger btn-sm" data-activateUser="'+ row.AspNetUserId +'">Activate</button>';
}
For further details about renderers, please check this

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.

datatables with ajax response

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
}

How do I add button on each row in datatable?

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!

Categories