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
Related
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.
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;
} }
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>'
}
}
]
});
});```
HTML :
<div class="datatable-header">
<button type="button" name="add" id="add" class="float-right btn btn-info">Add</button>
</div>
<div class="table-responsive">
<table class="table datatable-basic table-striped table-hover table-bordered"
data-data-url="<?= $this->url('bla/blabla/ajax', ['action' => 'list']) ?>
id="text-dataTable"
>
<thead>
<tr>
<th>Text</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
JQuery:
const textTable = $('#text-dataTable');
const textDataTable = textTable.DataTable({
"lengthMenu": [[10, 25, 50, 75, -1], [10, 25, 50, 75, "All"]],
"dom": '<"top"fBr><"datatable-scroll-wrap"t><"bottom mt-2"ilp>',
"lengthChange": true,
"pageLength": 25,
"autoWidth": false,
"searching": false,
"order": [[0, 'asc']],
"ajax": {
"url": textTable.data('data-url'),
"type": "POST"
},
"columnDefs": [
{ targets: [1], className: "text-center"},
],
"columns": [
{ data: "text", "render": function (data, type, full, meta) {
return '<textarea style="width: 100%" contenteditable id="text" class="update" data-id="'+full.id+'" data-column="text">' + data + '</textarea>';
}
},
{ data: "textId", "render": function (data, type, full, meta) {
let $html = '<a class="btn bg-success m-1 update" data-id="'+data+'"><i class="icon-floppy-disk"></i> Update</a>';
$html += '<a class="btn bg-danger m-1 remove" data-id="'+data+'"><i class="icon-trash"></i> Delete</a>';
$html += '<a class="btn bg-grey m-1 reset" data-id="'+data+'"><i class="icon-reset"></i> Reset</a>';
return $html;
}
},
],
"rowCallback": function (row, data, index) {
if (data.hasOwnProperty('rowClass')) {
$(row).attr('class', data.rowClass);
}
$('td:last', row).attr('class', 'text-center');
}
});
$('#add').click(function(){
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
}
);
textDataTable.draw( false );
const addedRowNode = addedRow.node();
$(addedRowNode).addClass('highlight');
});
Result:
it's updating the text for the first column and the data-id of the second column, my goal is to add a new empty row, which means i want the first column to have 'aa' and the second column to have 'bb' instead of the buttons. I tried hundreds of things in vain.
See Screenshot:
Second Thing I tried: which is a problem because if the user adds multiple rows at the same time and click insert one by one, it will always insert the value of the first new row added, since it's getting the value by id. And all the new rows have the same ID.
$('#add').click(function(){
let html = '<tr>';
html += '<td><textarea contenteditable id="new-row-text">aa</textarea></td>';
html += '<td><a class="btn bg-grey m-1 insert"><i class="icon-plus22"></i> Insert</a></td>';
html += '</tr>';
$('#text-dataTable tbody').prepend(html);
});
textDataTable.on('click', 'a.insert', function(){
swal.fire({
title: 'Are You Sure?',
showCancelButton: true,
confirmButtonClass: "btn-success",
reverseButtons: true,
showLoaderOnConfirm: true,
preConfirm: function (data) {
return new Promise(function (resolve, reject) {
$.post(
textDataTable.data('insert-url'),
{
text: $('#new-row-text').val()
},
(function data($data) {
resolve()
}),
'json'
).fail((function(xhr, status, error) {
swal.fire('Error', xhr.responseJSON.error, 'error');
}));
})
}
}).then(result => {
if (result.value) {
textDataTable.ajax.reload();
} else {
}
}, (function () {
}));
});
Solution:
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
"newRow": true
}
);
Then in the render function test to see if the newRow flag exists:
{ data: "textId", "render": function (data, type, full, meta) {
// Return data if new row
if (full.hasOwnProperty('newRow') {
return data;
}
.
.
},
Credit User 2Fkthorngren: https://datatables.net/forums/discussion/61522/problem-with-adding-new-empty-row/p1?new=1
I'm using DataTables pluging for Jquery, this is what I'm trying to do:
$('#familiars').DataTable({
processing: true,
serverSide: true,
ajax: "/familiars/list/",
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'lastname' },
{ data: 'age' },
{ data: 'country' },
{ data: 'address' },
{ data: 'id', render : function (data, type, row){
btn='<a class="btn btn-success" href="#" data-toggle="modal" data-target="#modal-edit" onclick="setRow( \'' +row+ '\' )"/><i class="fa fa-edit"></i> Edit</a>';
return btn;
}
},
],
});
function setRow(row){
console.log(JSON.stringify(row));
console.log(row);
console.log(row.id);
console.log(row.name);
}
Pass the row parameter through the function to get all the data from the row and use it to a edit form modal but in the function setRow I only get object Object in all that's trys
If I use for example row.name or data in the onclick="setRow( \'' +row+ '\' )"/ get the info but I want get all in the row parameter or another way to get all the row info to the function.
Thanks for the help!