Delete row from localStorage in Datatables after ordering - javascript

I'm testing Datatables plugin and need some advice. My problem is that I can't delete a specific row in my table after ordering. For removing rows I use .index() method. Here is my fiddle
At first I find closest row:
var row = $(this).closest('tr');
then using this code to set index number:
var index = $("#example tbody").children().index(row);
And of course after ordering this index number changes.
Can you suggest something more efficient?

Considering name as unique entry:
var name = $(row).find('td:first').text();
for (var i = 0; i < dataSort.length; i++) {
if (dataSort[i][0] == name) {
break;
}
}
dataSort.splice(i, 1);
Fiddle here

this may be the code u needed...
var row = $(this).closest('tr');
var nRow = row[0];
dataTable.dataTable().fnDeleteRow(nRow);

Related

Javascript to Jquery for loops

I would like to convert these for loops into jQuery but I am unsure how to do this. I am also unsure of how to convert document.querySelector. I tried to convert it like this:
$('.table1 tbody')
but it does not work when you call
tablebody.row[]
This is my code:
var headertext = [],
headers = $(".table1 th"),
tablebody = document.querySelector(".table1 tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
Thanks
You can use map() to create an array from the attributes of the specified th elements. You can then loop through that array and set the data attribute on the required td elements.
That being said, you can change the logic entirely to do this in a single each() loop. Try this:
var $headers = $('.table1 th');
$('tr > td').each(function(i) {
$(this).data('th', $headers.eq($(this).index()).text().replace(/\r?\n|\r/, ""));
});
Working example
Note that jQuery keeps data attributes in an internal cache, so you won't see any changes to the DOM with the above code (which is why in the jsFiddle example I set the text() too). This is absolutely fine, you just need to remember to use jQuery's getter signature of data() to retrieve the attribute.
For your reference, your attempt to convert querySelector to $('.table1 tbody') didn't work because the jQuery version returns a jQuery object, not a DOMElement, and jQuery object's don't have rows property.
You can use each function in jquery to iterate over elements.
$('.table1 th').each(function(index){
var text=$(this).text();
});
And
$('.table1 tbody td').each(function(index){
var tdObject=$(this);
// loop for iterating over all the TDs of table.
// You can use tdObject to get text, class and other values.
// e.g. var id = tdObject.attr('id');
var text=tdObject.text();
});

Remove all child nodes but the first one

I have an HTML table. The first row contains a checkbox. There is a javascript method associated to the checkbox change. If the checkbox is checked, the code adds a few rows to the table and fills them. If the checkbox is unchecked, the code removes all rows but the first one (the one that contains the checkbox).
The first part of the code works fine : the rows are properly added.
I have an issue with the second part. Here is my code :
if (checkboxValue) {
//Add first row
var tr1 = document.createElement("tr");
var td1_1 = document.createElement("td");
....
tr1.appendChild(td1_1);
var td1_2 = document.createElement("td");
...
tr1.appendChild(td1_2);
table.appendChild(tr1);
//Add second row
var tr2 = document.createElement("tr");
var td2_1 = document.createElement("td");
...
tr2.appendChild(td2_1);
var td2_2 = document.createElement("td");
...
tr2.appendChild(td2_2);
table.appendChild(tr2);
} else {
//Remove all rows but the first
var rows = table.getElementsByTagName("tr");
var nbrRows = rows.length;
if (nbrRows > 1) {
for (var i = 1; i < nbrRows; i++) {
var row = rows[i];
row.parentNode.removeChild(row);
}
}
}
The issue always come from rows[2] being undefined. I have no idea why!
If, instead of using removeChild, I write row.innerHTML = "", I have the visual effect I am looking for (all rows gone), but this is inelegant, since the table now contains several empty rows (their number increasing everytime I check/uncheck the checkbox).
A clue? Thank you very much for your time!
Don't use for-loop to remove DOM elements like this. The problem is that rows is a live collection, meaning that it updates every time you remove elements from DOM. As the result, i counter shifts and eventually you hit "undefined" element spot.
Instead, use while loop. For example, to remove all rows except the first one you could do:
var rows = table.getElementsByTagName("tr");
while (rows.length > 1) {
rows[1].parentNode.removeChild(rows[1]);
}
Also note, that it's getElementsByTagName without s.
UPD. Or iterate backward if you like for-loops better:
var rows = table.getElementsByTagName("tr");
for (var i = rows.length - 1; i > 0; i--) {
rows[i].parentNode.removeChild(rows[i]);
}
Demo: https://jsfiddle.net/9y03co6w/
you remove a row from the array you are iterating over. This is always a bad idea and probably the reason for your error.
solution: start iterating from the end instead of the beginning.
also see for example: example
try to replace this line
var rows = table.getElementsByTagNames("tr");
by
var rows = table.find("tr");

Set HTML table rows all at once

I currently have code that runs through every row of a html table and updates it with a different row.
Here is the code
function sort(index) {
var rows = $table.find('tbody tr');
var a = $table.find('tbody tr');
//Only sort if it has not been sorted yet and the index not the same
if(sortedIndex === index){
for(var i = 0; i < rows.length; i++){
a[i].outerHTML = rows[(rows.length - i)-1].outerHTML;
}
toggleSorted();
}else{
sortedIndex = index;
rows.sort(naturalSort);
for (var i = 0; i < rows.length; i++) {
a[i].outerHTML = rows[i].outerHTML;
}
sortedDown = true;
}
$('#${tableId}').trigger('repaginate');
};
What I am trying to do is to instead of going through every single row in the for loop and setting a[i].outterHTML = rows[i].outterHTML; I would like to just set all of the rows at once. Currently it takes about 1.5 seconds to set them and that is very slow.... Only issue is I cannot seem to find a way to do this. Is this actually possible? (It takes 1.5 seconds on large data sets which is what I am working with).
Since the rows are the same just reordered, you can .append them with the new order:
var $tBody = $table.find('tbody');
var $rows = $tBody.find('tr');
if(sortedIndex === index){
toggleSorted();
$tBody.append($rows.get().reverse());
}
else {
sortedIndex = index;
sortedDown = true;
$tBody.append($rows.get().sort(naturalSort));
}
Here's a fiddle that demonstrates the above: http://jsfiddle.net/k4u45Lnn/1/
Unfortunately the only way to "set all of your rows at once" is to loop through all of your rows and perform an operation on each row. There may be some libraries which have methods and functions that make it look like you're doing the operation on all of your rows at one shot, but ultimately if you want to edit every element in a set you need to iterate through the set and carry out the action on each element, seeing as HTML doesn't really provide any way to logically "link" the attributes of your elements.

Insert a table row alphabetically ordered in the table

I have a table which is alphabetically ordered by name (using PHP mysql), now I would like to insert a new row at the correct position in the table without doing a new request to the server. Is there any way to go through the table checking every name and insert the new row at the correct position using jQuery/Javascript?
You could also insert it in the end (or anywhere), and then re-sort the entire table using js/jquery:
var table = $('table'),
rows = $('tr', table);
$('#sortIt').click(function () {
rows.sort(function(a, b) {
var keyA = $('td',a).text();
var keyB = $('td',b).text();
return (keyA > keyB) ? 1 : 0;
});
rows.each(function(index, row) {
table.append(row);
});
});
Example here at jsFiddle.
There are a lot of ways, this is just the one of them using jquery:
let's set your new name and new row el
var newName = 'YourNewName'
var newRow = $('<tr>') // created new row element with cells
get list of names, add newName and sort them; let's say your name column is 2
var names = $('td:nth-child(2)').map(function () {return $(this).text()})
names.push(newName)
var sorted = names.sort()
getting position of added name
var newNamePos = sorted.indexOf(newName)
inserting new row to found position
$('tr:nth-child(' + (newNamePos + 1) + ')').before(newRow)

Deleting table rows in javascript

I'm having trouble with a function in javascript and can't figure out why. It's really quite straight forward. I'm trying to delete all the rows in a html table. so I wrote:
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
table.deleteRow(i);
}
}
Yet, it'll only delete half of them. Can anyone see what's causing this strange behavior?
Because when you delete the first row, the second row will become the first, it's dynamic.
You could do like:
while(table.rows.length > 0) {
table.deleteRow(0);
}
Consider this:
index 0: row #1
index 1: row #2
index 2: row #3
index 3: row #4
index 4: row #5
you delete index #2 (row #3), so the DOM engine adjusts the index keys and you end up with:
index 0: row #1
index 1: row #2
index 2: row #4 <---hey! index #2 is still there
index 3: row #5
You're basically digging a hole in the spot where you're standing, so as you dig deeper, you naturally sink deeper and never see any progress... until you run out of rows to delete in the table.
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i=rowcount-1; i >=0; i--) {
table.deleteRow(i);
}
}
The index of the row changes when you delete it. Use a reverse loop. This will also be helpful if you are using any condition to delete rows. If you are deleting all rows,use the following
while(table.rows.length) {
table.deleteRow(0);
}
If you delete the first row, the second row becomes the new first row.
I prefer to do this:
while(table.rows[0]) table.deleteRow(0);
You could just go:
document.getElementById("gameboard").innerHTML = "";
The table rows is live, that is if you delete row 0 then the next row becomes row 0, just constantly delete row 0
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i=0; i < rowCount; i++) {
table.deleteRow(0);
}
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
If you are using JQuery in your code then the easiest way to delete the rows is using the following code:
$('#myTable tbody').html('');

Categories

Resources