How to (re)load data in jQuery event functions? - javascript

The following code is based on the jQuery event example at https://datatables.net/examples/advanced_init/events_live.html
The data is displayed in the table as expected. However, clicking a row returns: "You clicked on undefined's row", i.e. there is no value assigned where I would expect the file_id of the respective row.
I guess that the json data from '../api/data/uploads/' has to be realoded, however, I cannot figure out how.
Many thanks for your help.
$(document).ready(function() {
var tab_uploads= $('#tab_uploads').DataTable( {
"stateSave": true,
"stateDuration": -1,
"ajax": {
"url": '../api/data/uploads/',
"dataSrc": 'data'
},
"columns": [{ "data": 'file_id', "title": 'File ID' },
{ 'data': 'username', "title": 'Uploading user' },
{ 'data': 'supplier_id', "title": 'Supplier ID' },
{ 'data': 'timestamp', "title": 'Timestamp' },
],
"dom": 'Bfrtip',
"buttons": ['pageLength', 'copy', 'csv', 'excel'],
"order": [],
});
$('#tab_uploads tbody').on('click', 'tr', function () {
var data = tab_uploads.row( this ).data();
alert( 'You clicked on ' + data[0] + '\'s row' );
} );
});

I found a solution based on this discussion: https://datatables.net/forums/discussion/57563/datatable-returns-undefined-when-i-try-to-print-rowdata-in-console
Since you are using columns.data to define your columns the data
structure is objects not arrays. Instead of data[0] you need to use
data.id
Which translates into using alert( 'You clicked on ' + data.file_id + '\'s row' ); in the code above.

Related

Populate a datatable starting from the second column

I have a datatable that retrieves json data from an api. The first column of the table should only contain a checkbox. However, when retrieving the data it populates the first column as well.
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
$('#parametrictable').DataTable({
data : json.data,
columns : json.columns,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
})
});
Is there any way that I can set that the data should only populate starting from the second column, leaving the first column to only contain the checkbox?
You can fix this issue by updating the api or in your js code just updating the data key value to null for first object in the json.columns array like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
json.columns[0].data = null;
json.columns[0].defaultContent = '';
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
.... your rest of code
})
});
EDIT:
I meant what your suggestion only did was hide the data that was overlapping with the checkbox. I don't want it hidden. I want the first column to be, by default, only checkboxes. and the overlapping data should be on the 2nd column.
You can update your API like this to achieve that:
"columns": [
{
"data": null,
"defaultContent": ""
},
{
"data": "DT_RowId",
"title": "Id"
},
{
"data": "supplier",
"title": "supplier"
},
{
"data": "color",
"title": "color"
}
],
Or, you can update your code without modifying your API like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
// Add object for checkbox at first position
json.columns.unshift({"data": null, "defaultContent": ""});
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
....your rest of code
})
});

Capture If DataTable JSON/AJAX GET Populates Correctly Using 'Success/Error'

I have a DataTable which is doing a GET but i was thinking that protection will be required to help improve UI and can display some sort of error so the user knows if the data is not displayed that an error has occurred and isn't sat watching a black screen.
Any way i know how to do this in a POST but was wondering if there is a way of doing it in a GET.
Current 'Working code
var existingRuleTable = $('#existingRulesDataTable').DataTable({
"ordering": false, // Allows ordering
"searching": false, // Searchbox
"paging": true, // Pagination
"info": false, // Shows 'Showing X of X' information
"pagingType": 'simple_numbers', // Shows Previous, page numbers & next buttons only
"pageLength": 10, // Defaults number of rows to display in table. If changing this value change the show/hide below
"dom": '<"top"f>rt<"bottom"lp><"clear">', // Positions table elements
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], // Sets up the amount of records to display
"fnDrawCallback": function () {
if ($('#dialPlanListTable').DataTable().rows().count() < 11) {
$("div[class='bottom']").hide(); // Hides paginator & dropdown if less than 11 records returned
} else {
$("div[class='bottom']").show(); // Shows paginator & dropdown if 11 or more records are returned
}
},
'ajax': {
"type": 'GET',
"url": "js/dataTable.json",
"data": function (data) {
return data;
}
},
"columns": [ // Display JSON data in table
{ "data": "position" },
{ "data": "startTime" },
{ "data": "endTime" },
{ "data": "selectedDays" },
{ "data": "selectedDates" },
{ "data": "selectedMonths" },
{ "data": "timeRange" },
{
"data": null,
"render": function (data) {
if (buttonclicked == 'Modify') { // Displays the radio button when 'Mod' clicked
return '<label class="c-radio" style="margin-bottom: 0px">'
+ '<input type="radio" name="existingRuleActionRadioButton" value="option1">'
+ '<span class="fa fa-check"></span>'
+ '</label>';
} else if (buttonclicked == 'Delete') { // Displays the delete button when 'Del' clicked
return '<button name="deleteRuleButton" class="btn btn-danger" id="' + data.position + '">'
+ '<i class="fa fa-trash-o" style="font-size: large"></i>'
+ '</button>';
} else {
return ''; // Needed for the 'Add' button click
}
}
}
]
});
Things i have tried
Added this at the end which works BUT i don't know the state (success/error)
"initComplete": function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
}
Then tried the blow AJAX which fires and dropd into the correct 'Success/Error' but this then does not render my DataTable
'ajax': {
"type": 'GET',
"url": "js/dataTable.json",
"data": function (data) {
return data;
},
success: function(data){
alert('Success');
},
error: function(e){
alert('Failed');
}
},
Datatables provides a number of events that can be hooked into:
https://datatables.net/reference/event/
In this case, rather than use initComplete (which seems to be for the DataTables 'Editor' plugin), it looks like the event to hook into is the error event:
https://datatables.net/reference/event/error
You could also look into the draw and xhr events.
It looks like using success: and error: on the ajax: property is overwriting dataTables use of those to render the table; this could be why the xhr event is exposed rather than expose the underlying ajax promise.

Adding an element within a td in jQuery datatable

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

Jquery Datatables Checkbox selected append to input field

the btnSearchName will open a Modal with table of the search result, then it has checkbox per row to select, then after I click the btnSubmit, the Modal will close and must put the selected ssn_or_tin column in an input field like '123, 645, 936, 743', I already tried many codes but not working, please help
$('#btnSearchName').on("click", function() {
Namestable = $('#NamesDatatable').DataTable({
"processing": true,
'select': {
'style': 'multi'
},
'order': [[1, 'asc']],
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
defaultContent: '',
className: 'select-checkbox',
'checkboxes': {
'selectRow': true
},
orderable: false
},
{ "data": "ssn_or_tin", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
});
$('#btnSubmit').on("click", function () {
var rows_selected = Namestable.column(0).checkboxes.selected(); //i have not tested this line of code yet if it's working,
maybe there is another way of getting the selected checkbox, maybe by their class if they have the 'selected' class
$.each(rows_selected, function () {
$('#txtSSNTIN').append(
//I don't know what code to put here, it must append the
'ssn_or_tin' values like '123, 953, 673' in the input field with
the id 'txtSSNTIN'
);
});
});
You could have try Onrowbound in DataTable. You dont have to specify these things

add tooltip to specific column of datatables

I have table defined in html as <table id="tableDynamic"></table>
And I am updating table dynamically as
$('#tableDynamic').DataTable( {
columns: [
{ title: data[0] },
{ title: data[1] },
{ title: data[2] },
],
"columnDefs": [
{
"render": function (data, type, row){
return '<a>' + row[0] +'</a>';
},
"targets": 0
},
]
} );
}
How can I add tooltip just to specific column data[2]
You could also do it like this (call any other javascript after Datable initialisation is complete):
$('#tableID').DataTable({
[...]
fnDrawCallback: function(oSettings, json) {
//Call JS here
alert( 'DataTables has finished its initialisation.' );
tooltip('.selector', 'theme');
}
});
I asked a somewhat similar question here. Look at YouneL answer for more details, and an example to do the same with a call back.

Categories