4

I can't seem to find this anywhere. I have a dataTable like this one, and I want to be able to count the number of rows in the dataTable in javascript. how would that be accomplished? thanks!

I need it in javascript because I want to iterate through the datatable and check to see if any rows cantain certain data in them.

EXAMPLE PSEUDOCODE

var tableSize = someway to get table size;
for (i = 0; i < tableSize; i++) {
if (dataTable.row(i).value == "someValue") {
    //do something
}
GG.
  • 21,083
  • 14
  • 84
  • 130
Myy
  • 18,107
  • 11
  • 37
  • 57

4 Answers4

14

It would be easier to count the rows with jQuery:

var tableSize = $('#myTable tbody tr').length;

Demo: http://jsfiddle.net/YLVuK/1/

GG.
  • 21,083
  • 14
  • 84
  • 130
1

Using jQuery, you could simply do

var tableSize = $("#myTable").find("tbody").find("td").length;

And name your table with an ID of "myTable"

bluedevil2k
  • 9,366
  • 8
  • 43
  • 57
0

if your table has an id, you can do it as follows:

var table = document.getElementById("tableId");
for(var i = 0, ceiling = table.rows.length; i < ceiling; i++) {
    var row = table.rows[i]; // this gets you every row
    for(var j = 0, ceiling2 = row.cells[j]; j < ceiling2; j++) {
        var cell = row.cells[j]; // this gets you every cell of the current row in the loop
        var cellContent = cell.innerHTML; // this gets you the content of the current cell in the loop
    }
}
Tom
  • 4,096
  • 2
  • 24
  • 38
0

You can count the number of rows in a datatable on the server side in your backing bean and then set a java object attribute equal to the number of rows. Then in your view, you can set the javascript variable using el expression language. Something like this:

Backing bean:

public class backer() {
    List<Cars> cars = new ArrayList<Cars>();

    public List<Cars> getCars() {
        return cars;
    }

    public void setCars(List<Cars> cars) {
        this.cars = cars;
    }

    public int numCars() {
        return cars.size();
    }
}

In your xhtml file:

var tableSize = #{backer.numCars}
Catfish
  • 18,876
  • 54
  • 209
  • 353