3

I am trying to make a simple while loop to count the number of rows in the table #offices, and I have no idea why this isn't working, but the alert keeps returning 0...

html:

<table id="offices" class="table table-striped">
    <caption class="text-left">
      <p class="lead">Current List of Offices</p>
    </caption>
    <thead>
        <tr>
            <th>Office Name</th>
            <th>Office abrev.</th>
            <th>Display Order</th>
            <th>Edit</th>
            <!-- TMPL_UNLESS is_agent -->
            <th>Delete</th>
            <!-- /TMPL_UNLESS -->
        </tr>
    </thead>
    <tbody>
    <!-- TMPL_LOOP Office_loop -->
    <tr>
        <td><!-- TMPL_VAR office_name --></td>
        <td><!-- TMPL_VAR short_name --></td>
        <td><!-- TMPL_VAR sequence_number ESCAPE=0 --></td>
        <td><a href="https://stackoverflow.com/office/edit/<!-- TMPL_VAR office_id -->"><i class="fa fa-edit"></i> Edit Office</a></td>
        <!-- TMPL_UNLESS is_agent GLOBAL=1 -->
        <td><a href="https://stackoverflow.com/office/delete/<!-- TMPL_VAR office_id -->"><i class="fa fa-trash-o"></i> Delete Office</a></td>
        <!-- /TMPL_UNLESS -->
    </tr>
    <!-- /TMPL_LOOP -->
    </tbody>
</table>

js/jquery:

var rowCount = $("#offices > tr").length;
alert(rowCount);
var i = 0;
while ( ++i <= rowCount ) {
    console.log( "counting rows: " + i );
}
4
  • Use $("#offices tr") Commented Oct 21, 2014 at 6:30
  • @Satpal i need to target the tbody tr specifically so i dont count the thead rows. Commented Oct 21, 2014 at 6:33
  • put it in (document).ready still notta Commented Oct 21, 2014 at 6:33
  • Then use $("#offices > tbody > tr") Commented Oct 21, 2014 at 6:34

3 Answers 3

11

Try with this:

$('#tabId tbody').find('tr').length;
Sign up to request clarification or add additional context in comments.

Comments

3

you can use

var rowCount = $('#tableId tr').length;

Comments

1

Use $("#offices tbody tr") instead of $("#offices > tr")

> is a looks for immediate children.

1 Comment

yea $("#offices tbody tr") worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.