I am adding a new row in the datatable and its working correctly, I am ordering the table by a field (which is timestamp) which means the newly created row should have index 0 and the rows should be 1,2,3...
however the problem is that the new row is giving -1 when I check its index. So, how can I actually re-order the table when I add a new row so that the newly created row should have index 0?
var myTable = $('#myTable').DataTable();
var rowNode = myTable
.row.add([ btnHtml1, btnHtml ])
.draw();
when I check the index after it has been added:
rowindex = tr.index(); //this gives -1 for the newly created row
Can anyone suggest why is it giving the wrong index?
UPDATE:
function myFunction(this_) {
var tr = $(this_).closest("tr");
rowindex = tr.index(); //this gives the displayed index of the row, NOT the real index
}
I call it from the datatable row like this:
<td>
<button type="button" id="edit_button" onclick='myFunction(this)' name="edit_button">Edit</button>
</td>
I am not able to recreate your problem.
But I am not sure where the tr variable is defined - so, that may be causing an issue.
For a simple test, here is some data:
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Row Index</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>0</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>1</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>2</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>3</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>4</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>5</td>
</tr>
</tbody>
</table>
And here is a test for the data:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable();
var rowNode = table.row.add( ['Quinn Flynn', '?'] ).draw();
console.log(rowNode.index());
});
</script>
This prints 6 to the browser console - the new row has an index of 6, as expected.
Another way to verify this is to loop through all the rows, showing the index of each one:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable();
var rowNode = table.row.add( ['Quinn Flynn', '?'] ).draw();
table.rows().every( function () {
console.log(this.index());
});
});
</script>
This generates the following output in the browser console:
Here we can see that the row for "Quinn Flynn" has the expected index: 6.
Update
Some additional notes based on comments in the answer:
The row index assigned to a row does not change, once it has been assigned, until the row is deleted, or if the data is replaced and refreshed.
Index values are assigned based on the order of the data provided to DataTables - so, for example, in my case, the first row in my HTML table is for "Tiger Nixon" - so that is assigned row index 0. The same applies to data provided by a JSON object.
The row index is independent of the display order of the row (due to sorting and/or filtering).
When you add a new row to DataTables, it is added to the end of the existing rows inside DataTables - and is indexed accordingly. So, my new row is assigned index 6.
It sounds like you want to take the first row as displayed in the table regardless of what its index number is.
There is a shortcut you can use to get that:
console.log(table.row().data());
In my example, this returns an array:
[ "Airi Satou", "4" ]
It works because it uses row() - not rows() and therefore defaults to fetching only one row (the first row!) from the displayed table.
Be aware that if you provide your data as objects, you may not get an array like my example - you may get an object - for example, something like this:
{ "firstName": "Airi Satou", "index": "4" }
Suppose you have a html table of the
<form id="myForm">
<table id="myTable">
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
<tr>
<td>Alpha</td>
<td>Bravo</td>
<td>X</td>
</tr>
<tr>
<td>Charlie</td>
<td>Delta</td>
<td>X</td>
</tr>
<tr>
<td>Echo</td>
<td>Foxtrot</td>
<td>X</td>
</tr>
</table>
</form>
Reset
I have the following javascript
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID)
{
table.deleteRow(rowID);
}
function reset()
{
form.innerHTML = formSave;
}
For some reason, the remove() function works fine, but after using the reset() function, it no longer works. Can anyone tell me why this is?
As var table is a live 'Element object' it's properties are updated each time you delete a row. By the time you deploy the reset() function var table references less Children than the restored HTML. Opening the console will show you have an indexing error on subsequent uses of the function bound to "X".
You can remedy this by re-acquiring the element in the reset function, like so...
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID) {
table.deleteRow(rowID);
}
function reset() {
form.innerHTML = formSave;
/* re-acquire 'new' (inserted) table */
table = document.getElementById('myTable');
}
Hope that helped :)
using php to echo json array inline i want js/jquery to populate table according to these data.
HTML table
<table>
<thead>
<tr>
<th>Time</th>
<th data-day='2013-03-15'>15-3</th>
<th data-day='2013-03-16'>16-3</th>
<th data-day='2013-03-17'>17-3</th>
</tr>
</thead>
<tbody>
<tr data-time='09'>
<td>9am</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"09:00:00"},
{"date":"2013-03-15","id":"1","time_booked":"09:10:00"},
{"date":"2013-03-17","id":"5","time_booked":"09:30:00"}
];
$.each(arr,function(){
console.log('id:'+this.id+'inside:'+this.date+'|'+this.time_booked);
});
</script>
i want to loop thro arr and according to its date and time_booked write id inside td.
for example first row will go to td with date-day='2013-03-15' and data-time='09'
so how can i do this using javascript ?
im thinking should i include data-day,data-time inside each td in tbody ? or is there a better way to do it ?
current approach:
include data-day inside each tr so html of tbody is
<tr data-time='09'>
<td data-day='2013-03-15'></td>
<td data-day='2013-03-16'></td>
etc..
</tr>
then use js
$.each(arr,function(){
var rday=this.date;
var rtime=this.time_booked;
var sel='tr[data-hr="'+rtime.substr(0,2)+'"]';
var dom=$(sel).find('td[data-day="'+rday+'"]').first();
if(dom.length)dom.append(this.id);
});
but i have a feeling its stupid ! there must be a way to map table using x,y (table head,row head) or there is none ?
I think the jQuery index function is what you're looking for. In the code sample below, I've used it to fetch the colIndex for the date. In this case, it fetches all of the th cells within the table, and uses .index(..) with a selector seeking the required date. This gives the column index of the date you're seeking, and from there it's all pretty straight-forward.
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"0900"},
{"date":"2013-03-15","id":"1","time_booked":"0910"},
{"date":"2013-03-17","id":"5","time_booked":"0930"}
];
$.each(arr,function(){
var cell = GetCellByDateAndTime(this.date, this.time_booked);
$(cell).text(this.id);
});
function GetCellByDateAndTime(date, time) {
var colIndex = $("#BookingsTable th").index($("[data-day='" + date + "']"));
var row = $("#BookingsTable tr[data-time='" + time + "']")
var cell = $(row).children($("td"))[colIndex];
return cell;
}
And a Fiddle.
How can I delete all rows of an HTML table except the <th>'s using Javascript, and without looping through all the rows in the table? I have a very huge table and I don't want to freeze the UI while I'm looping through the rows to delete them
this will remove all the rows:
$("#table_of_items tr").remove();
Keep the <th> row in a <thead> and the other rows in a <tbody> then replace the <tbody> with a new, empty one.
i.e.
var new_tbody = document.createElement('tbody');
populate_with_new_rows(new_tbody);
old_tbody.parentNode.replaceChild(new_tbody, old_tbody)
Very crude, but this also works:
var Table = document.getElementById("mytable");
Table.innerHTML = "";
Points to note, on the Watch out for common mistakes:
If your start index is 0 (or some index from begin), then, the correct code is:
var tableHeaderRowCount = 1;
var table = document.getElementById('WRITE_YOUR_HTML_TABLE_NAME_HERE');
var rowCount = table.rows.length;
for (var i = tableHeaderRowCount; i < rowCount; i++) {
table.deleteRow(tableHeaderRowCount);
}
NOTES
1. the argument for deleteRow is fixed
this is required since as we delete a row, the number of rows decrease.
i.e; by the time i reaches (rows.length - 1), or even before that row is already deleted, so you will have some error/exception (or a silent one).
2. the rowCount is taken before the for loop starts
since as we delete the "table.rows.length" will keep on changing, so again you have some issue, that only odd or even rows only gets deleted.
Hope that helps.
This is an old question, however I recently had a similar issue.
I wrote this code to solve it:
var elmtTable = document.getElementById('TABLE_ID_HERE');
var tableRows = elmtTable.getElementsByTagName('tr');
var rowCount = tableRows.length;
for (var x=rowCount-1; x>0; x--) {
elmtTable.removeChild(tableRows[x]);
}
That will remove all rows, except the first.
Cheers!
If you can declare an ID for tbody you can simply run this function:
var node = document.getElementById("tablebody");
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
Assuming you have just one table so you can reference it with just the type.
If you don't want to delete the headers:
$("tbody").children().remove()
otherwise:
$("table").children().remove()
hope it helps!
I needed to delete all rows except the first and solution posted by #strat but that resulted in uncaught exception (referencing Node in context where it does not exist). The following worked for me.
var myTable = document.getElementById("myTable");
var rowCount = myTable.rows.length;
for (var x=rowCount-1; x>0; x--) {
myTable.deleteRow(x);
}
the give below code works great.
It removes all rows except header row. So this code really t
$("#Your_Table tr>td").remove();
this would work iteration deletetion in HTML table in native
document.querySelectorAll("table tbody tr").forEach(function(e){e.remove()})
Assing some id to tbody tag. i.e. . After this, the following line should retain the table header/footer and remove all the rows.
document.getElementById("yourID").innerHTML="";
And, if you want the entire table (header/rows/footer) to wipe out, then set the id at table level i.e.
How about this:
When the page first loads, do this:
var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;
Then when you want to clear the table:
myTable.innerHTML=myTable.oldHTML;
The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.
If you do not want to remove th and just want to remove the rows inside, this is working perfectly.
var tb = document.getElementById('tableId');
while(tb.rows.length > 1) {
tb.deleteRow(1);
}
Pure javascript, no loops and preserving headers:
function restartTable(){
const tbody = document.getElementById("tblDetail").getElementsByTagName('tbody')[0];
tbody.innerHTML = "";
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<table id="tblDetail" class="table table-bordered table-hover table-ligth table-sm table-striped">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 2</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a
</td>
<td>
b
</td>
<td>
c
</td>
<td>
d
</td>
</tr>
<tr>
<td>
1
</td>
<td>
2
</td>
<td>
3
</td>
<td>
4
</td>
<tr>
<td>
e
</td>
<td>
f
</td>
<td>
g
</td>
<td>
h
</td>
</tr>
</tr>
</tbody>
</table>
<button type="button" onclick="restartTable()">restart table</button>
If you have far fewer <th> rows than non-<th> rows, you could collect all the <th> rows into a string, remove the entire table, and then write <table>thstring</table> where the table used to be.
EDIT: Where, obviously, "thstring" is the html for all of the rows of <th>s.
This works in IE without even having to declare a var for the table and will delete all rows:
for(var i = 0; i < resultsTable.rows.length;)
{
resultsTable.deleteRow(i);
}
this is a simple code I just wrote to solve this, without removing the header row (first one).
var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}
Hope it works for you!!.
Assign an id or a class for your tbody.
document.querySelector("#tbodyId").remove();
document.querySelectorAll(".tbodyClass").remove();
You can name your id or class how you want, not necessarily #tbodyId or .tbodyClass.
#lkan's answer worked for me, however to leave the first row, change
from
for (var x=rowCount-1; x>0; x--)
to
for (var x=rowCount-1; x>1; x--)
Full code:
var myTable = document.getElementById("myTable");
var rowCount = myTable.rows.length;
for (var x=rowCount-1; x>1; x--) {
myTable.deleteRow(x);
}
This will remove all of the rows except the <th>:
document.querySelectorAll("td").forEach(function (data) {
data.parentNode.remove();
});
Same thing I faced. So I come up with the solution by which you don't have to Unset the heading of table only remove the data..
<script>
var tablebody =document.getElementById('myTableBody');
tablebody.innerHTML = "";
</script>
<table>
<thead>
</thead>
<tbody id='myTableBody'>
</tbody>
</table>
Try this out will work properly...
Assuming the <table> element is accessible (e.g. by id), you can select the table body child node and then remove each child until no more remain. If you have structured your HTML table properly, namely with table headers in the <thead> element, this will only remove the table rows.
We use lastElementChild to preserve all non-element (namely #text nodes and ) children of the parent (but not their descendants). See this SO answer for a more general example, as well as an analysis of various methods to remove all of an element's children.
const tableEl = document.getElementById('my-table');
const tableBodyEl = tableEl.querySelector('tbody');
// or, directly get the <tbody> element if its id is known
// const tableBodyEl = document.getElementById('table-rows');
while (tableBodyEl.lastElementChild) {
tableBodyEl.removeChild(tableBodyEl.lastElementChild);
}
<table id="my-table">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody id="table-rows">
<tr>
<td>Apple</td>
<td>Red</td>
</tr>
<!-- comment child preserved -->
text child preserved
<tr>
<td>Banana</td>
<td>Yellow</td>
</tr>
<tr>
<td>Plum</td>
<td>Purple</td>
</tr>
</tbody>
</table>
Just Clear the table body.
$("#tblbody").html("");
const table = document.querySelector('table');
table.innerHTML === ' ' ? null : table.innerHTML = ' ';
The above code worked fine for me. It checks to see if the table contains any data and then clears everything including the header.
I want reorder table rows using JavaScript .
for example take the following dummy table:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
</tr>
</table>
I want to do this in JavaScript without using jQuery. I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row.
I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?
If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it:
<table id="mytable">
...
</table>
<script type="text/javascript">
var tbl = document.getElementById('mytable');
var rows = tbl.getElementsByTagName('tr');
var firstRow = rows[0];
var lastRow = rows[rows.length];
firstRow.parentNode.insertBefore(lastRow.parentNode.removeChild(lastRow), firstRow);
</script>
Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.
Do:
var table = ...; // Get reference to table (by ID or other means)
var lastRow = table.rows[table.rows.length - 1];
lastRow.parent.insertBefore(table.rows[0], lastRow);
The best way to solve this in Javascript is:
Give the Tr.. a unique name. for eg: X_Y,X_Z,A_Y,A_Z
Now add a hidden lable or text Box which gives the sorting order from the server i.e When the page renders I want to sort it All the Tr's that have a ID starting with A should come first and All the Z's should come second.
<asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X</label>
<asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y</label>
When the page renders..the order should be A_Z,A_Y,X_Z,X_Y
Before Rendering this is table that comes from the aspx file:
<table>
<tr id='Tr_Heading'>
<td>A</td>
<td>B</td>
</tr>
<tr id="Tr_X_Y">
<td>GH</td>
<td>GH1</td>
</tr>
<tr id="tr_X_Z">
<td>HU</td>
<td>HU1</td>
</tr>
<tr id="tr_A_Z">
<td>JI</td>
<td>JI1</td>
</tr>
<tr id="tr_A_Y">
<td>JI</td>
<td>JI1</td>
</tr>
Script:
function SortAndArrange()
{
var firstList = document.getElementById('lblFirstSortOrder').value;
var secondList = document.getElementById('lblSecondSortOrder').value;
var firstTypes = new Array();
firstTypes = firstList.split(',');
var secondLists = new Array();
secondLists = secondList.split(',');
var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]);
for (var i = 0; i<firstTypes.length; i++)
{
for (var j = 0; j< secondTypes.length;j++)
{
var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j];
var FirstSecondTrs = document.getElementById(TrName);
if (FirstSecondTrs)
{
FirstSecondTrs.parentNode.removeChild(FirstSecondTrs);
insertAfter(refNode,FirstSecondTrs);
refNode = FirstSecondTrs;
}
}
}
}
function insertAfter( referenceNode, newNode )
{
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page...
Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution.
Thanks,
Ben