Add extra column to existing table populated with datatables - javascript

I am populating a table with datatables. The table has four columns always. But I need to add another column which can be shown or hidden based on boolean value.
My code so far:
{% show_extra_fields_button = show_extra_fields_bool %}
<table class="display" id="fields_datatable" class="fields_datatable">
<thead>
<tr>
<th>Name</th>
<th>Place</th>
<th>Email</th>
<th>Phone</th>
<th>Add Extra</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="/static/js/vendor/datatables.min.js"></script>
<script>
$(document).ready(function() {
$("#fields_datatable").dataTable({
ajax: {
"processing": true,
"dataSrc": "",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
]
})
if (show_extra_fields_button) {
$("#fields_datatable tr").each(function(){
$(this).append("<td><button>Add Extra</button</td>");
});
}
});
</script>
Here I would want to show the Add Extra column based on the boolean value. I want the header and the column values which will be buttons to be added using js.
How can I do that?

You can use data tables built-in functionality.
To add a button column you can use the following column definition:
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
Then use initComplete callback to set the columns' visibility once table has fully been initialised, data loaded and drawn:
$("#fields_datatable").dataTable({
ajax: {
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
],
"initComplete": function (settings, json) {
// get instance of datatable
table = settings.oInstance.api();
// get column using its name and set visibility
table.column('buttonColumn:name').visible(show_extra_fields_button);
}
});

You can put - instead of deleting that <td> for example <td>-</td>

You can add to the table header just the same way you are adding to the table body.
if (show_extra_fields_button) {
$('#fields_datatable thead tr').append('<th>Add Extra</th>')
}
Execute it just one time.

Related

How can I add Id to row with jquery ajax server-side

I need to add id property to TR of table data dynamically added with jquery ajax server-side and write data there. how can I do that. I add the Json data coming with the code below to the lines.
"ajax": {
"url": '/Siparis/SiparisleriDoldur/',
"type": 'POST',
"dataType": 'json',
"data": { liste }
},
"columns":
[
{ "data": "MusteriAdi", "name": "Müşteri Adı" },
{ "data": "MalzemeAdi", "name": " Ürün Adı" },
{ "data": "SiparisAdet", "name": "Sipariş Adedi" },
],
i want to do;
<tr id='IdNumber' data-id='IdNumber'>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
Note: IdNumber is in data(json list)
Given your use of the Datatable library you can use the createdRow property of the settings to amend each row as required. Try this:
$('#yourDatatable').dataTable({
"createdRow": function(row, data, dataIndex) {
let id = data[0]; // amend 'data[0]' here to be the correct column for your dataset
$(row).prop('id', id).data('id', id);
},
"ajax": {
// ...
},
// other settings as normal...
});
I fixed my problem with;
"createdRow": function (row, data) {
var id = data.Id;
$(row).prop('id', id).data('id', id);
$(row).attr('data-id', id).data('data-id', id);
},

How to replace standard bootstrap table with dataTables in jQuery?

I have tried and searching lot of solution but not solve my problem, even at dataTables website. The problem is how to display nested array in json using DataTables? Fo example below, How if I just want to display l3_id: "1" data only.
I try to understand this link but not really understand. Example
There is no error at console and network tab.
DataTable not appear, including dataTables features such as search box, pagination. (The CDN/library has been imported)
JSON
{
"data": [
{
"project_id": "1",
"l1_task": [
{
"l1_id": "1",
"l2_task": [
{
"l2_id": "1",
"l3_task": [
{
"l3_id": "1",
"l3_name": "My name"
}
]
}
]
}
]
}
]
}
JS (I am applying HTML in JS)
"<table id='Layer3Table' class='table dt-responsive nowrap' style='width:100%'>"+
"<thead>"+
"<tr>"+
"<th class='text-center'>ID</th>"+
"<th class='text-center'>Activity Name</th>"+
"</tr>"+
"</thead>"+
"</table>"+
$('#Layer3Table').DataTable({
ajax: {
url: url_project_detail",
dataSrc : "data"
},
columns: [
{ data : "l1_task.0.l2_task.0.l3_task.0.l3_id" },
{ data : "l1_task.0.l2_task.0.l3_task.0.l3_name" },
],
});
Either define your table, including all tbody content in HTML, then use DataTables to enable the search etc features. If you do it this way you don't need to set the url or columns (although you can still set other options).
$('#Layer3Table').DataTable();
Or if you want to make use of the url and column features, create the basic table structure in HTML
<table id='Layer3Table' class='table dt-responsive nowrap' style='width:100%'>
<thead>
<tr>
<th class='text-center'>Project ID</th>
<th class='text-center'>Project Name</th>
<th class='text-center'>Project Description</th>
<th class='text-center'>Project Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Then set up your DataTable separately in JavaScript.
$('#Layer3Table').DataTable( {
ajax: {
url: url_project_detail,
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: "application/json",
dataSrc : "data",
},
columns: [
{ data : "l3_id", "className": "text-center" },
{ data : "l3_name", "className": "text-center" },
{ data : "l3_description", "className": "text-center" },
{ data : "l3_status", "className": "text-center" }
],
});
What you appear to be doing is looping over your results and creating a DataTable for each of them, which is why it doesn't understand.

How do i change the color of value in a datatable cell when there is a change in the value of that cell

I am fetching json data through ajax for my datatable and performing a ajax reload every 2 seconds which updates the datatable values but I want to change the color of all the values that changed during the reload. How can I do that?
I would like the output to be like this
https://www.dailyfx.com/forex-rates?ref=TopRates
This is my code
<table id="example" class="pgnTable table" style="width:100%">
<thead>
<tr>
<th>First value</th>
<th>Second value</th>
<th>Third value</th>
<th>Fourth value</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable({
"ajax": {
"url": "/pktd",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
"columns": [{
"data": "first"
},
{
"data": "second"
},
{
"data": "third"
},
{
"data": "fourth"
}
]
});
setInterval(function() {
$('#example').DataTable().ajax.reload();
}, 2000);
});
</script>
You could set a CSS Class when you see a value change, with CSS Keyframes you can also add some color changing animations like the forex site.
JQuery has functions built in for adding and removing classes based on an elements ID like you have above.

How to get particular column in responsive jquery datatable for small Screen

I have implemented responsive jquery datatable in one of my project.
At the end of each row there is edit/detail link.
If i click edit/detail link:
1)Large Screen - It picks the UseID(Which is first Column in a row), so that i can edit that User.
2)Small Screen - Because of responsiveness the row will splitted as show below. It doesnot pick that User ID.
Large Screen Edit/Detail is Last row
Large Screen after clicking Edit link
Small Screen See Edit/detail link which is splitted
I am not able to get the UserID alert when i click edit link whenever the screen is small.
My Code.
<table id="myExample" class="display responsive nowrap">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>LastName</th>
<th>Street</th>
<th>City</th>
<th>Zip</th>
<th>State</th>
<th>Email</th>
<th>Edit</th>
</tr>
</thead>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTables.responsive.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#myExample').DataTable({
"ajax": {
"url": "/Admin/LoadData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Usr_Nm", "autowidth": true },
{ "data": "FirstName", "autowidth": true },
{ "data": "LastName", "autowidth": true },
{ "data": "Street", "autowidth": true },
{ "data": "City", "autowidth": true },
{ "data": "Zip", "autowidth": true },
{ "data": "Sate", "autowidth": true },
{
data: null,
defaultContent: 'Edit/Detail',
orderable: false
}
]
});
$('#myExample').on('click', 'a.Edit', function (e) {
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
$.ajax({
url: '/Admin/UserEdit',
type: "GET",
data: { 'id': UserId },
dataType: "json",
success: function (response) {
// alert('1:');
// alert(response);
if (response.isRedirect) {
// alert('1');
window.location.href = response.redirectUrl;
//window.location.href = response.redirectUrl;
}
// }
},
error: function (response) {
alert("Some error");
}
});
});
})
</script>
To get UserID:
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
Inspect Element in Large Screen
Inspect Element in Small Screen:
You must go through the dataTables API in order to get data for columns not present in the DOM (removed due to responsiveness).
You can get the all values for a certain row by table.row(<tr-node>).data() :
$('#myExample').on('click', 'a.Edit', function (e) {
var data = table.row($(this).closest('tr')).data()
//if it is "User Name" / first column you are after
var userId = data[0]
...
})

Jquery datatables does not display the column headers

This is linked to the question here. However, my case is a bit different. I would like to implement the same datatables example from the other question which is here. As you can see you have to pass the column names to be able to initialize the table headers like below
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
The problem is that I would not know the header names beforehand as they will change. I've tried initializing the column names when I get the data from ajax like below using a 3rd variable (see where it says 'pay attention to this line' but this doesn't work.
//PAY ATTENTION TO THIS LINE
var columnsHeaders = [];
var ab = $('#dynamicScenarioTable').DataTable({
"bDestroy": true,
"dom": 'T<"clear">lfrtip',
"ajax": {
"type": "POST",
"url": "dynamicScenario.htm",
"data": tags,
"dataType": "json",
"dataSrc": function(json){
//PAY ATTENTION TO THIS LINE
columnsHeaders.push({"data": json.header });
return json.vals;
},
"error": function(exception)
{
displayMessageOnError();
}
},
//PAY ATTENTION TO THIS LINE
"columns": [columnsHeaders],
tableTools: tableDefaultS.tableTools
});
Any ideas?
You can add a data-source attribute to the TH tags that are built on your table header. You can then have jQuery read those and construct the array to send into the DataTable constructor.
<tr>
<th data-source="name">Name</th>
<th data-source="position">Postion</th>
<th data-source="start_date">Start Date</th>
</tr>
Then in your JavaScript do something like this to construct the array
var columnsHeaders = [];
$("#dynamicScenarioTable thead th").each(function() {
colmnsHeaders.push(
{
data : $(this).data("source")
}
);
});
// construct your DataTable after this

Categories