How to repair a bad row selection from dataTable jquery? - javascript

I have two jquery dataTables in my php file. First table is loaded in the main file php from mysql database. The second table is loaded with ajax to the same php file but the content depend of row clicked on the first dataTable.
I have a problem, when I click the row of the first dataTable it loads the second table correctly. However when I click a row in the second dataTable not get some value, like not found the row. It show undefined value...
$(document).ready(function() {
**//I create dataTable 1**
var table = $('#example').DataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
}, "dom": '<"toolbar">frtip'
});
**//I create dataTable 2**
var table2 = $('#example2').DataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
}, "dom": '<"toolbar">frtip'
});
**//I load dataTable 1**
$('#example tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}else{
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
var getted = table.row('.selected').data();
$.ajax({
type:'POST',
data: 'usuario=' + getted,
url: 'loadF1.php',
success: function(msg) {
$('#example2 tbody').html(msg); //Here set content into div2
}
});
**//I load dataTable 2**
$('#example2 tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}else{
table2.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
var getted2 = table2.row('.selected').data();
$.ajax({
type:'POST',
data: 'usuario=' + getted2,
url: 'loadF2.php',
success: function(msg) {
$('#example3 tbody').html(msg); //Here set content into div3
}
});
What am I doing wrong, why when I select the second table it's not getting get the row selected?
Thanks!

Related

Leaflet feature click

I have a leaflet map with the boundaries of Europe countries. When the user clicks on a feature I get the name of Country by a field in geojson file.
I also have a datatable with data from database and I have a function on row click.
How I can perform a click on datatable row from leaflet feature click?
The problem: on feature click -> execute a function
With the below code I get Feature Name and search on datatable
layer_europe_with_data_0.on('click', function(e) {
var dd = e.layer.feature.properties.NAME_ENGL
var tbldump = $('#europetbl').DataTable();
tbldump.search(dd).draw();
}
One way was that I found the search option on datatable, so I can search on datatable for the row. But I can perform the click on.
The function on row click
$('#europetbl tbody').on('click', 'tr', function () {
// bla bla bla
}
I want to do this:
layer_europe_with_data_0.on('click', function(e) {
do this $('#europetbl tbody').on('click', 'tr', function () {
}
code for row click
$('#europetbl tbody').on('click', 'tr', function () {
var tbl = $('#europetbl').DataTable();
var dt = tbl.row( this ).data();
mymap.setView([dt[4], dt[3]],6)
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
tbl.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
$("#fetchtbl tbody").html("");
var id = dt[0];
idforcountrystats = id;
localStorage.setItem("idforstats", idforcountrystats);
$.ajax({
url: "fetchdata.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" data-id="'+ item.fetID+'"
onclick="QuickView(this)"></td><td>' + item.Fua_name + '</td></tr>' ;
});
$('#fetchtbl tbody').append(trHTML);
}
}
})
})

How to get the data-value of selected td

I want to get a data value from the clicked td, which opens a modal with the informations of the user.
When I select all users, everything works fine..
But when I want to search a specific user (table is not displayed until you search for a user), the modal shows not the right data..
I created a JS array with the usernames and put it in my data value. The innerHTML from the column is the first- and last name of the user.
The problem is that when I click on the name the modal shows the information from the FIRST user in my array (grouped by lastname ASC)
I'm using the DataTables plugin. Here's a short example of my drawCallback function:
"drawCallback": function(settings) {
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var last = null;
api.column(0, {
page: 'current'
}).data().each(function(group, i) {
if (last !== group) {
var groupName = api.row(i).data();
$(rows).eq(i).before(
'<tr class="group"><td style="font-weight: bold;" data-value="'+groupName[0]+'" data-toggle="modal" data-target="#profileModal" class="tdPerson" colspan="1">'+group+'</td><td colspan="5"></td></tr>'
);
last = group;
}
});
}
Here's my AJAX request:
$('.table').on('click', '.tdPerson', function(event) {
id = $(this).attr('data-value');
$.ajax({
url: "getData.php",
data: {
type: "getPersonModal",
data: id
},
type: "POST",
success: function(data) {
$('#profileModalContent').html(data);
}
});
});

jQuery datatable show span when update successful

I am using jQuery Datatables, and am working on an inline editing feature. I have been trying to get a green check to show when the record is updated.
Here is the ajax that populates the datatable:
$.ajax({
url: 'api/massEditorSummary.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR)
{
var jsonObject = $.parseJSON(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [
{ "data": "partner_name" },
{ "data": "service" },
{
"data": "forecast",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
{
$(nTd).html("<input type='text' class='form-control editForecast'
id='editForecast' data-uid='"+oData.UID+"' data-editforecast='"+oData.forecast+"'
value='"+oData.forecast+"' style='width:75px; height:30px;' />
<span id='testID' style='display: none;'><i class='fa fa-check' id='updatedIcon' aria-hidden='true'
style='color:green;'> </i></span>");
}
}
],
"stateSave": true,
"autoWidth": false
});
},
error: function(jqHHR, textStatus, errorThrown)
{
// show fail stuff
}
});
If you'll notice in the data column "forecast", I have a span with an ID set to testID. This span includes a font-awesome check icon. I initially set it to display: none.
Now I have this update feature that functions on BLUR event:
$('#example1').on('blur', 'tr > td > .editForecast', function(e)
e.preventDefault();
var uid = $(this).attr('data-uid');
var forecastcurval = $(this).attr('data-editforecast');
var forecastnewval = $(this).val();
var forecastData = '';
$.post('api/inlineEditProcess.php', {uid:uid, forecastcurval:forecastcurval, forecastnewval:forecastnewval}, function(data)
{
forecastData = data;
callForecastFunction(forecastData);
});
function callForecastFunction(forecastData)
{
if(forecastData == "Success")
{
$(this).css('display', 'inline-block'); // this is where I want to show the check
}
else
{
// do fail stuff
}
}
});
You'll see in the callForecastFunction function, if the data that is returned from the process script equals 'success', then show the check.
As mentioned above duplicate id attributes are not allowed. You should fix both the input and span id's. The span id you can base off the UID, for example:
"<span id='" + rowData.UID + "' style='display: none;'><i class='fa fa-check' id='updatedIcon' aria-hidden='true' style='color:green;'> </i></span>");
You can add additional text to make it more unique.
Then change the selector in your callForecastFunction() to select the span based on the UID:
$('#' + uid).css('display', 'inline-block'); // this is where I want to show the check
BTW, it looks like you are missing { in the event handler function:
$('#example1').on('blur', 'tr > td > .editForecast', function(e)

Child rows in DataTables using AJAX

I am trying to bind a child table with a parent table. I am not able to figure out how this can be done when the data for the child table is coming through an AJAX call which then creates a dynamic table.
I have followed this
Below is my code.
$('#myTable tbody).on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format()).show();
tr.addClass('shown');
}
});
function format() {
$.ajax({
type: 'GET',
url: '#Url.Action("MyFunction", "Home")',
data: { "Id": MyId },
dataType: "json",
async: false,
success: function (data) {
var list = data;
$.each(list, function (index, item) {
return '<table>.......<table />';
//i need to loop across the list and create a dynamic table with tr and td
});
},
error: function (result) {
var error = JSON.stringify(result);
throw "Error...";
}
});
}
$('#myTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
format(row.child); // create new if not exist
tr.addClass('shown');
}
});
and then the format() will be
function format(callback) {
$.ajax({
....
//async: false, you can use async
success: function (data) {
var list = data;
var html = '';
$.each(list, function (index, item) {
...
//create <tr> <td> with loop
html= '<tr><td>.......</tr>';
});
callback($('<table>' + html + '</table>')).show();
},
...
});
}
demo here jsfiddle

How to destroy first initialization of datatable (DataTable inside a modal)

I have a modal that displays a table. And I use datatable plugin so that the data is searchable and sortable. It works properly at first but when I close the modal and click other link to the same modal, it displays error. I have found solution to destroy the DataTable and I put the destroy() before the initialization of the datatable but then no data is displayed inside the table.. if I put it after the initialization it gave me the initialization error the second time I click the button. How am I going to solve this?
here's my code:
$.ajax({
url: "<?php echo site_url('admin/group/getMember')?>",
type: 'POST',
data: { 'groupID': id},
dataType: 'JSON',
success: function(result){
$('#records_table tbody').empty();
// $('#records_table').DataTable({
// "bLengthChange": false,
// "paging":false,
// });
$('.modal-header #hdrmsg').text(result[0].fname);
var trHTML='';
$.each(result, function (i, item) {
trHTML += '<tr><td>' + item.fname + '</td><td>' + item.mname + '</td><td>' + item.lname + '</td></tr>';
});
$('#records_table tbody').append(trHTML);
$('#records_table').DataTable({
"bLengthChange": false,
"paging":false,
});
$('#records_table').DataTable().fnDestroy();
}
});
The main reason for destroying a dataTables instance is if you want to change the initialisation options - like change paging and so on. Or if the table structure should be altered. None of those circumstances seems to be the case here? To answer the question, the safest way to destroy and reinitialise a table is to use the shorthand option destroy: true :
var table = $('#records_table').DataTable({
...
destroy : true
});
To go further, I think you are doing it a little backwards.
Why empty the table with jQuery $('#records_table tbody').empty(); instead of table.clear() ?
Why inject records with jQuery $('#records_table tbody').append(trHTML); instead of using table.row.add([...]) ?
Here is a code scenario similar to the one in the question, which reinitialises the dataTable without conflicts, each time the modal is shown :
var table;
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table, if it exists
if (table) table.clear();
//reinitialise the dataTable
table = $('#records_table').DataTable({
destroy: true,
bLengthChange: false,
paging: false
});
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
see demo -> http://jsfiddle.net/bz958dxj/
But you really dont need to destroy the table at all, it just slows down performance :
//global table object
table = $('#records_table').DataTable({
bLengthChange: false,
paging: false
});
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table
table.clear();
//insert data
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
demo -> http://jsfiddle.net/8mjke9ua/
NB: I just assume we are talking about bootstrap modals, based on the reference to .modal-header in the question.
NBĀ²: Notice the $.parseJSON(response.contents), you should do it as you are doing it in the question. The only reason for this is that the examples go trough a proxy to avoid the same-origin policy.

Categories

Resources