Iterate of each table in accordion only once using jQuery

437 views Asked by At

I have an accordion with 5 sections. Inside each section is a table. If that table has more than 10 rows a View More link is appended. My problem is that the View More link is appended 5 time in the first table. 4 time in the second table. 3 time in the third table. And so on...

How do I append the View More link just once on every table where there are more than 10 (or 2) rows.

$(".accordion-group table tbody").each(function() {

    var row = $(this).find("tr");
    var colunm = $(this).find("tr:first td");

    row.last().addClass("last");

    var rowCount = row.length;
    var columnCount = colunm.length;

    if (rowCount > 10) {
        $("<tr><td colspan=" + columnCount + " class=\"view_more_accordian\" style=\"text-align:center;\">View more</td></tr>").insertAfter(".last");
    }
}); });

Thanks in advance for you help.

1

There are 1 answers

4
PSL On BEST ANSWER

Reason is that in your insertAfter selctor you provide tbody and which will return all of them and insert after all of the available tbody's, instead just append it to the current tbody i.e this.

Change

$("<tfoot><tr><td colspan=" + columnCount + " class=\"view_more_accordian\" style=\"text-align:center;\">View more</td></tr></tfoot>")
  .insertAfter("tbody");

to

$("<tfoot><tr><td colspan=" + columnCount + " class=\"view_more_accordian\" style=\"text-align:center;\">View more</td></tr></tfoot>")
  .insertAfter(this);

Also you can avoid using the first .each (based on your shown code) instead you can just do

$(".accordion-group table tbody").each(function () {
...
});