user284503
user284503

Reputation: 378

jQuery table count rows always returns value of 1

For some reason every time I try to count the number of rows in a table it always returns 1. I am dynamically adding and removing rows to the table, so I'm starting to think it is just counting the number of rows initially configured in the table. here is the code I'm using.

$(".elementDelRowButton").live ('click', function (event) {

console.log ($(this).closest('table').length);
                  if ($(this).closest('tr').index()!=0) {
                      $(this).parent().parent().remove();
                  }

            });

I have tried using Size, length and other variations, it always returns 1.

Here is the HTML:

<table id="element_items"><tr>
  <td><input type="radio" name="radio" /></td>
  <td><input type="text" value="RadioItem"/></td>
  <td><span class="elementAddRowButton">+</span>/<span class="elementDelRowButton">-</span></td>
</tr>
</table>

Upvotes: 2

Views: 2980

Answers (3)

user284503
user284503

Reputation: 378

Thanks everyone.. this worked for my situation:

console.log ($(this).closest('table').find('tr').length);

Upvotes: 0

Luca Rocchi
Luca Rocchi

Reputation: 6484

console.log ($(this).closest('table').length); just return a jquery set that contains the closest tag "table" ... The set contains one element indeeed , the table itself, as closest return the first parent that match

console.log ($(this).closest('table').children("tr").length should gives the rows count

Upvotes: 2

David Morton
David Morton

Reputation: 16505

It could be that there's a tbody in your source surrounding all of your rows. Try this:

console.log($(this).closest('table').find('tr').length);

By the way, the "this.parent().parent().remove()" looks dangerous. You may want to use a selector along with the "closest" function.

Upvotes: 4

Related Questions