Thursday, January 24, 2013

Enumerate Html Table Rows with JS/JQ Example

i was asked so that all the page tables will get a running number for their row, AND to keep these numbers with only ++ after filter, so lets go.
how do i add a cells, a TD to an existing row TR? suprisingly super easy

var firstRow = document.getElementById("myTable").rows[0];
var x = firstRow.insertCell(0);
x.innerHTML = "New cell";

cool. not lets spam all tables with a new cell
var newCellIndex = 0;

function AddNumerationsCells() {
    var allTables = $("table");
    for (var i = 0; i < allTables.length; i++) {
        allRows = allTables[i].rows;
          if (allRows[j].cells[0].tagName == "TH") {
                var newTH = document.createElement('th');
                newTH.innerHTML = "Row Number";
                var firstCell = allRows[j].cells[0];
                allRows[j].insertBefore(newTH, firstCell);
            }
           
else {
                var newCell = allRows[j].insertCell(newCellIndex);
            }
    }
    ResetNumerations();
}


awesome. and enumerate them, but only the visible ones

function ResetNumerations() {
    var allTables = $("table");
    for (var i = 0; i < allTables.length; i++) {
        allRows = allTables[i].rows;
       
var index = 0;
        for (var j = 0; j < allRows.length; j++) {
           if (allRows[j].cells[0].tagName != "TH") {
                if (allRows[j].style.display != "none") {
                   allRows[j].cells[newCellIndex].innerHTML = index++;
                }

           }
        }
    }
}


PEOPLE!! were so done :), take a look http://jsbin.com/owanex/5/edit

hey - we can do it shorter with JQ

function AddNumerationsCells() {
    $("table tr >:nth-child(1)").each(function (index, elem) {
        $(this).clone().text(function () {

            return elem.tagName == 'TH' ? 'RowNumber' : ''
        }).insertBefore($(this));
    });
    ResetNumerations();
}

function ResetNumerations() {
    $("table").each(function () {
        $(this).find("tr:visible").find("td:eq(0)").each(function (index) {
             this.innerHTML = ++index;
        });
    });
}


live: http://jsbin.com/owanex/15/edit

p.s. for the JQ part i must thx Royi Namir for the push and for the AddEnumerationCells part, took me 10 mins to understand and read it so i'll explain.
nth-child() is a bit similar to eq() but not. while eq() depends on the left part the nth-child() isnt and therefor we can put it with nothing before (like td or th).
and since we dont know what tag of element we get but now we can get it we can just call clone() to clone the same element.
since we're here counting of the table to have only text we're calling text() to set whatever text we want, we could also call html(), and there we put our if for the th case.
finally we have the JQ insert before to finish the job.
THX ROYI!

No comments:

Post a Comment