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
Related
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.
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);
},
I have a js data table that I have implemented for pagination of data. It uses the jQuery data table. The data is being displayed correctly. However, I want to add an element within the first row of the data table.
Before I added it like this : <td>#Html.ActionLink(item.CarId, "Detail", "Cars", new { id = item.CarId},null)
<span class="dt-expand-btn js-expand-btn">+</span></td>
What I want to add within the td of the js is : <span class="dt-expand-btn js-expand-btn">+</span>
var carsDataTable = $('.js-cars-lists').DataTable({
"ajax": {
"url": "/Cars/CarsPagination",
"processing": true,
"serverSide": true,
"language": {
"paginate": {
"previous": '<i class="material-icons">chevron_left</i>',
"next": '<i class="material-icons">chevron_right</i>'
}
},
"order": [0, "asc"],
"type": "POST",
"datatype": "json"
},
"columns": [
{
"data": "CarId", "name": "CarId", "autowidth": true,
"render": function (data, type, row, meta) {
$(row.CarId).css('color', 'red');
return '' + row.CarId + '';
}
},
{ "data": "CarName", "name": "CarName", "autowidth": true },
Could someone please help me to achieve this ? Also, paginate icons are not appearing. Please help.
jQuery DataTable has a function of render it accepts 4 parameters function(data, type, row) which you can control the rendering of your rows. You can now check the rows of a table and add your element in it.
You can use columnDefs method and then render:
...
columnDefs: [{
"render": function(data, type) {
return '<span class="dt-expand-btn js-expand-btn">+</span>';
},
"targets": 0
}]
...
targets refers to the index of the table column (since you are referring to the 1st column) set it to 0
I'm using the jquery DataTables plugin to display an array of objects. I would like to clear the table and redraw using the changed data. However, the only way I've been able to do that so far is to destroy the table and reinitialize. I'd like to know if there is a simple way to refresh from JS data source. This is what I'm doing, it works but feels wrong...
if (NAMESPACE.table){
NAMESPACE.table.destroy();
}
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
]
});
if you want to clear the data present in dataTable simply call table.clear() it clears all cells in table.
and then add new data using table.row.add().draw();
table.destroy() does not removes data present in cell of table, it only destroys the current instance of dataTable you created.
Make it simpler:
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
],
"destroy": true
});
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)