Assigning Row_Ids to dynamically added rows in Datatables - javascript

I am working on making an editable Datatable using Jeditable. I need to be able to dynamically add rows, which I have successfully done. By default, it appears that Datatables will add everything with a row_id of 0, which makes it impossible to differentiate added rows from each other.
So I am working on a function that assigns the row_id. There are no errors, but it also does not seem to work as it still returns a row_id of 0 for all added rows.
$('#addRow').on( 'click', function () {
var rowIndex = $('#example').dataTable().fnAddData([ "column1Data", "column2Data"]);
var row = $('#example').dataTable().fnGetNodes(rowIndex);
$(row).attr('id', row_id_counter);
row_id_counter ++;
Entire code:
http://jsfiddle.net/j2frzerj/

I tested your code in the fiddle provided, and it is adding new table rows with sequential id's, starting with index 0. I am not seeing any duplicate id's of 0?
http://prntscr.com/ew3tg9
http://prntscr.com/ew3tlr

Related

JavaScript Add onclick functions with row number as parameter to dynamically generated rows

The Problem
Hi, I am making a table in which I have two buttons, View and Update for each row. I am generating the rows in one for loop. Since I am using innerHTML, Instead of adding the onclick listeners there, I make another for loop after the first one and add the event listeners there. The event listeners are added to all rows. However, the parameter( Row number) passed in functions for all rows is the number for the last row.
Not sure why this is happening, any clues or advice will be helpful. I will leave the relevant code and debugging results below.
The Code
Adding New Rows
table.innerHTML="";
var count=1;
querySnapshot.forEach((doc) => {
var innerhtml='<tr id="row">.....</tr>';
//Append the new row
table.innerHtML=table.innerHTML+innerhtml;
//Assign new ID to row
document.getElementById("row").id=count.toString()+"row";
//Increment Count for next row/iteration
count=count+i;
});
Adding event Listeners for Each Rows
for(var i=1;i<count;i++){
console.log("Adding functions for row : "+i);
//Get/Generate ID of rows (ID was assigned with same logic)
var cchkid=i.toString()+"chk";
var uupdateid=i.toString()+"update";
console.log("Adding functions for row : "+cchkid + " "+uupdateid);
//Add Listeners for Each button in row i
document.getElementById(cchkid).addEventListener("click", function(){
alert("adding check function for id : "+i);
check(i-1);
});
document.getElementById(uupdateid).addEventListener("click", function(){
alert("adding update function for id : "+i);
update(i-1);
});
}
Debugging by using Console Log & Inspect
Count : 3
Adding functions for row : 1
Adding functions for row : 1chk 1update
Adding functions for row : 2
Adding functions for row : 2chk 2update
Inspect
Using inspect element, I can ensure that all rows have separate id's
So far everything looks good, However, when console logged inside the said functions, all rows give the same value for the passed parameter.
Console Log after clicking on two different rows
2 Display data for user ID: 1
This should be :
Display data for user ID: 0 for first row
Display data for user ID: 1 for second row and so on
I cannot figure out what's wrong here, kindly help this newbie out. Thanks!
The answer was simple but took me a little while to figure out. When assigning eventlisteners in a loop, I was using var for the iterator. That is, for(var i=0;i<length;i++). However Inside the listener, the var i doesnot exist even if the listener is added inside the loop because of the scope of var in JS.
for(var i=0.......){
button.addeventlistener("click",function(){ myFunc(i); }));
}
Changing the var here to let does the trick here. That's it.

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.

Deleting dynamically created rows in Knockout.js

I'm using knockout.js 2.3.0 and I have a table with dynamically added rows and select lists in each of these rows. Upon changing a date input, the select lists populate with different content. Because different dates will populate the lists with different content, I want to remove any previously added rows because the content may not be accurate.
The issue I'm having is that not all of the rows are being removed. Ex: If I have more than 4 rows, there will always be 2 remaining. The only time all rows are cleared is when there is only 1 row to start with.
Here's the subscribed function for deleting the rows
self.date.subscribe(function() {
//I also tried setting the loop length to a very long number but the same results happened each time
for (i = 0; i < self.customers().length; i++){
self.customers.remove(self.customers()[i]);
}
//now populate the select list and add an empty row - commented out for testing to make sure rows are being deleted
//setCustomerList(self.date());
//self.customers.push(new AddCustomer(self.customerList[0]));
});
I was just testing to see what would happen, and the only way I've gotten all of the rows to remove is by adding multiple for loops which obviously isn't desirable.
Is there a simpler way to remove all dynamically added rows?
If you want to remove all the items in an observable array, use the removeAll method:
self.customers.removeAll();
If you really want to use a loop, you could do so by continuously removing the last (or first) item until there are none left:
while (self.customers().length) {
self.customers.pop();
}
I think you need to reverse the for loop and remove the items from the bottom up. the problem with your code is that the each time an item is removed the length of the array changes.
self.date.subscribe(function() {
var customerLength = self.customers().length
for (i = customerLength ; i >= 0; i = i - 1){
self.customers.remove(self.customers()[i]);
}
});

Determine row and column index of input in table

I'm working on creating a javascript based spreadsheet application. Right now I can dynamically create the spreadsheet as a table with a supplied number of rows and columns and a text input in each cell as can be seen in this picture.
I'd like to have a generic event tied to all of the inputs in the table in which I am able to determine the row index and column index of the input that fired the event. Something like this:
$('.spreadsheet-cell').click(function () {
var rowIndex = $(this).attr('rowIndex');
var columnIndex = $(this).attr('columnIndex');
});
I originally tried implementing things by dynamically adding row and column index attributes to the html input element when I create it but when I add rows or columns after the original spreadsheet has been created things get messy trying to shift the value of these attributes around. I think I could make that method work if it came down to it but it seems messy and I'd prefer not to mess around so much with the DOM when I figure that there is probably some way using jQuery to determine the relative index of the parent <td> and <tr>.
Use jQuery .index. Within your function:
var rowIndex = $("#table tr").index($(this).closest('tr'));
var colIndex = $("#table td").index(this);

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