jQuery DataTable : Delete row and reload - javascript

Now, I am working with jQuery DataTable. Everything is going well in intializing data tables with javascript data array.
In my table, it included remove row button. When I clicked the Remove button of each row, I delete record using following function.
function removeRow(itemList, recordIndex){
itemList.splice(recordIndex, 1);
dataTable.clear();
dataTable.rows.add(itemList);
dataTable.columns.adjust().draw(false);
}
This function performed well with no error. At that, I set false to draw() function to prevent going to first page when delete records in any other page.This one also working for me.
The problem is, when my itemList has 11 records, and I go to second page of data table and delete the 11th record.
So, my itemList will left only 10 record and My data table should show the first page of paging.
But, jQuery data table is not doing that. It still have in second page with no records.
I don't know how to fix that one. I want to show previous page after delete every records from current page.
I know `draw()`` function without false parameter will go to first page. But it go to first page in every deletion.
I only want to go to previous page, when I deleted all records from current page.
Please, help me. Thanks.

I found an hacky way to get the previous pagination when the current has been emptied.
It is specific to jQuery DataTable, since using it's class naming.
Try it in CodePen.
function removeRow(recordIndex){
// Get previous pagination number
var previousPagination= parseInt( $(document).find(".paginate_button.current").data("dt-idx") ) -1;
// Splice the data.
data.splice(recordIndex,1);
myTable.clear();
myTable.rows.add(data);
myTable.columns.adjust().draw(false); // May ajust the pagination as empty... `.draw(false)` is needed.
// Decide to redraw or not based on the presence of `.deleteBtn` elements.
var doIdraw=false;
if($(document).find(".deleteBtn").length==0){
doIdraw=true;
}
myTable.columns.adjust().draw(doIdraw); // Re-draw the whole dataTable to pagination 1
// If the page redraws and a previous pagination existed (except the first)
if(previousPagination>1 && doIdraw){
var previousPage = $(document).find("[data-dt-idx='" + previousPagination + "']").click();
}
// Just to debug... Console.log the fact that only one pagination is left. You can remove that.
if(previousPagination==0 && doIdraw){
}
}
Notice that I used:
#myTable as the table id
.deleteBtn as the delete buttons class
data as the dataTable data
I removed all console.log() and example related code in the code above (but not in CodePen).
"Delete this →" button handler is:
$("#myTable").on("click",".deleteBtn",function(){
var rowElement = $(this).closest("tr");
var rowIndex = myTable.row(rowElement).index();
removeRow(rowIndex);
});

Related

How to add jquery tabledit buttons to new rows of a table

How to tell to jQuery tabledit that the rows are changed? The buttons only generated for existing rows, when I add a new row (for example using jQuery), the table buttons doesn’t appear in the new row. I saw in tabledit code, that there is possibility to switch between view and edit mode (maybe this would help me), but don’t know how to access these methods after the tabledit is created and when rows has been changed.
A little snippet from my code:
$(document).ready(function(){
$(‘#btn’).click(function(){ ... adding row, I need to update tabledit here });
$(‘#table’).Tabledit(...parameters...); }
});
tabledit
Here is the best solution I could come up with for your situation.
I created an "Add" button. NOTE the for-table attribute so I can figure out what table to add to later.
<button id='add' for-table='#example1'>Add Row</button>
Then I created a click handler for the "Add" button.
$("#add").click(function(e){
var table = $(this).attr('for-table'); //get the target table selector
var $tr = $(table + ">tbody>tr:last-child").clone(true, true); //clone the last row
var nextID = parseInt($tr.find("input.tabledit-identifier").val()) + 1; //get the ID and add one.
$tr.find("input.tabledit-identifier").val(nextID); //set the row identifier
$tr.find("span.tabledit-identifier").text(nextID); //set the row identifier
$(table + ">tbody").append($tr); //add the row to the table
$tr.find(".tabledit-edit-button").click(); //pretend to click the edit button
$tr.find("input:not([type=hidden]), select").val(""); //wipe out the inputs.
});
Essentially;
Deep Clone the last row of the table. (copies the data and attached events)
Determine and set the row identifier.
Append the new row.
Automatically click the Edit button.
Clear all inputs and selects.
In my limited testing this technique appears to work.
jQuery Tabledit should be executed every time a table is reloaded. See answer given here:
refreshing Tabledit after pagination
This means that every time you reload the table (e.g. navigating to new page, refreshing etc), you must initialize Tabledit on the page of the table where it wasn't initialized. The problem is that there is no way to know whether Tabledit has been initialized on the table already, hence if you re-initialize it, duplicate buttons (edit, delete..) will be added to the rows of the table. You also cannot destroy a non-existent Tabledit, hence calling 'destroy' always beforehand will not help.
I hence created my own function to tell me if Tabledit is initialized on a certain page of a table or not:
function hasTabledit($table) {
return $('tbody tr:first td:last > div', $table).hasClass("tabledit-toolbar");
}
and using it as follows:
if( !hasTabledit($('#table')) ) {
$('#table').Tabledit({
url: 'example.php',
columns: {
identifier: [0, 'id'],
editable: [[1, 'points'], [2, 'notes']]
},
editButton: true,
deleteButton: false
});
}
The hasTabledit(..) function checks whether the last cell of the first row of the table has a div which has the tabledit-toolbar class, since this is the div that holds the Tabledit buttons. You may improve it as you like. This is not the perfect solution but it is the best I could do.

Odd behavior when removing action buttons from a table in JavaScript

I have a page that builds a table using DataTables, and each row has an Action Button that adds some data (an ID, just an int) from that row to a list. To keep users from clicking each action button multiple times, I made it so a row's button is removed the first time you click it. This worked great until I realized the buttons come back if you switch to the next page of the table and then switch back to the first page.
To fix this, I wrote some JS to compare each row to my list of data, and if that row's data is already in the list, it removes that row's action button. This happens each time the table is reloaded (for example, when you switch to a different page of the table and back again) using DataTable's draw.dt function.
The problem is, when I switch pages and the JavaScript goes to work removing buttons, for some reason it skips every other row. For example, if I click (thus removing) the first three rows' action buttons, switch pages and switch back, my JS removes the action buttons on row 1, 3, and 5 instead of rows 1, 2, and 3. It's so consistent that it has to be some kind of simple looping error due to my sloppy JS skills, but I can't find it.
Here is the code:
$(document).on('draw.dt', function () {
var $allSerialNumbers = $('.box-electrode'); // This is a list of all the rows' action buttons / ID's
$('#electrodes li').each(function (i, li) { // This is the list of ID's I'm comparing to
var $id = $(li).data('id');
for(var index = 0; index < $allSerialNumbers.length; index++){
if($id == $allSerialNumbers.eq(index).attr('data-id')){ // For each item in my ID list, run through all the rows and see if any Action Button ID's match any on the list
$('.box-electrode').eq(index).remove(); // If they do match, remove that Action Button
}
}
})
});
I'm not an expert on JQuery, but could remove() in your last line be re-sizing the list so that the element which used to be at index 1 is now at index 0, causing you to skip it when you increment the index?

Refresh Datatable 1.9 without deleting all the rows

I'm using dataTables js 1.9
An ajax call to the server get's information from the server that I want to be displayed in the table every 60 seconds or so.
I have no problems implementing solution that clears table and repopulates it:
$(id).dataTable().fnClearTable();
for( var i = 0 ; i < json.response.length; i++ ){
$(id).dataTable().fnAddData([ json.response[i] ]);
}
Issue is that the user will get pushed back to page 1 each tome the reload happens since table will be empty momentarily and it will only have 1 page then.
I would like to implement a solution where I first search for rows not in the result, remove those, then add rows that are not in the table. For this I would need to be able to target a row by a value, and I cannot find it in http://datatables.net/docs/DataTables/1.9.4/DataTable.html
Anyone has any ideas on how to do this?
You don't need to delete the data and re-populate it, you just need to redraw it.
var oTable = $("table").dataTable({ ... your settings ... });
//redraws the table
oTable.fnDraw();

How to refresh DataTables after call to page event?

Here is my scenario ...
I am using pagination with DataTables. My first column is css styled based upon data that is passed in. So, I display the correct colored icon for the property of the item in the table. Everything on page 1 displays correctly. Just doing the basics, everything on further pages does not get displayed because it is removed from the DOM at that time.
So, I did $('#my_id').on('page.dt', function() {perPageFunctionCall();}).dataTable(so on an so forth)}; to call a function which selects the correct colored flag.
When I click on page 2, nothing gets updated. I click on page 1 again and it redisplays the 1st page correctly. I click on page 2 a second time now and it displays everything correctly this time.
So what is causing the display not to update with my new css the 1st trip but to display properly on subsequent trips? Is there someway to refresh the element or the data table after I am done with my css manipulation?
Well it is one of two things:
Either it is
1: I added
.on( 'order.dt', function () { perPageFunctionCall(); } )
.on( 'search.dt', function () { perPageFunctionCall(); } )
in addition to my page function call.
But more likely everyone's favorite reason:
2: Caching
In either case, it does work flawlessly now as expected.
for refresh resp. table :
var path = "/server_processing.php";
var dt = $('#tableid').DataTable();
dt.clear();
dt.draw();
dt.ajax.url(path).load()

Add rows to a JQuery DataTable without redrawing

How can you add rows to a JQuery DataTable without redrawing the entire table?
The behavior I would like is for it to find the correct location (based on the sort) to insert the row into the table while maintaining scroll position of the table and pagination if any.
I was facing the same problem. The solution i found for this were a new function with the name
fnStandingRedraw http://datatables.net/plug-ins/api/fnStandingRedraw.
I added the above code to be able to use this function,
$.fn.dataTableExt.oApi.fnStandingRedraw = function (oSettings) {
if (oSettings.oFeatures.bServerSide === false) {
var before = oSettings._iDisplayStart;
oSettings.oApi._fnReDraw(oSettings);
// iDisplayStart has been reset to zero - so lets change it back
oSettings._iDisplayStart = before;
oSettings.oApi._fnCalculateEnd(oSettings);
}
// draw the 'current' page
oSettings.oApi._fnDraw(oSettings);
};
After that i execute the following commands,
theTable.fnAddData([reply], false);
theTable.fnStandingRedraw();
where,
theTable: is the datatable variable (var theTable = $('#example').dataTable();).
reply: is the information i add to a row of mine datatable. More on http://datatables.net/plug-ins/api/fnStandingRedraw.
The first command adds a row on the table without redrawing it. After this, the new row will not being displayed on the table.
The second command redraws the table, so the new raw will appear, but retain the current pagination settings.
This worked fine for me.
Use dataTable().fnAddData()
http://datatables.net/ref#fnAddData
Example:
http://www.datatables.net/release-datatables/examples/api/add_row.html

Categories

Resources