2

I have a table with various columns and many rows. To simplify this, I just need to know how many rows are billable (in this case, column 2). In other words, how many rows in column 2 have the text "y"? Anyways, this is what I've tried so far:

jQuery

var billable = 0;

// attempt 1
table.rows().eq(1)( function () {
    if(table.data() === 'y'){
       //priceTotal+=parseInt(table.cell(row,0).data());
        alert('This is the billable column, now count which equal "y".')
        billable++;
    }
});  

// attempt 2
column(2).data() === "y"){
    alert('This is the billable column, now count which equal "y".')
    billable++;
}

http://jsfiddle.net/s827x/3/

1
  • have you considered using angularjs? Commented Aug 4, 2014 at 19:48

3 Answers 3

2

with jquery we can select element by the index in the parent Element: :nth-child(), so simply:

$( ".our-table td:nth-child(2):contains('y')" ).length;

Just added to HTML (just in case):

<tbody class="our-table">

and using the :contains() Selector, we selecting all the <td> in column 2, that :contains('y')

demo: http://jsfiddle.net/s827x/6/

Sign up to request clarification or add additional context in comments.

3 Comments

This works nicely for currently shown rows, but doesn't count the entire datatable. I have 197 rows.
@triplethreat77, can you please Give an example of your large table?, I tried with a large table and it seems to work. jsbin.com/porosoyu/1/edit
also, datatables removes / injects <tr>'s / <td>'s when it filter rows / show/hide columns, so you could easily get a wrong result.
1

Use the dataTables API to cycle through all the rows :

var rowCount = table.rows()[0].length;
for (var row=0;row<rowCount;row++) {
    if (table.cells(row, 1).data().indexOf('y')>-1) {
        billable++;
    }
}
alert(billable+' total');

forked fiddle -> http://jsfiddle.net/3C9Rk/

Note : Cells is zerobased, and the number of rows can be found multiple ways, the above is just an API example.

Comments

0

isherwood's example would work for an exact match, but this would also work if you're only looking for matches that contain a search term:

function countContaining(table, search) {
  var count = 0;
  $(table).find('td').each(function(e) {
    if (e.innerHTML.indexOf(search) > 0) {
      count++;
    }
  });
  return count;
}

1 Comment

table is a datatables API object, not a jQuery object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.