Numbering dynamic table rows

I'm working on making a dynamic HTML table using jQuery. In a table, my user has two interactions:

  1. Append a row
  2. Remove a specific row

The problem with numbering the rows is that if a user removes a specific row, all of the rows following that row need to be renumbered. I would have to select all rows following the removed row and subtract their number by 1.

Is there a better way to go about this?

EDIT: Here's a JSFiddle demonstrating the problem:

I'm aware that an ordered-list would automatically renumber my rows, but I'd rather use a table since the example I'm giving now is pretty boiled-down.



First, wrap the counter number in a <span> with a class for easy finding later:

$new_row.children('td').prepend('Row #<span class="num">' + ($new_row.index() + 1) + "</span>");

Then update all these spans with an .each loop after you remove the desired row. The first argument passed into .each's callback function is a zero-based index number, and the second is the HTML element:

    var $row = $(this).closest('tr'),
        $table = $row.closest('table');

    $table.find('tr').each(function(i, v) {
        $(v).find('span.num').text(i + 1);

After the user has appended a row, or deleted one, you just need to iterate over the "number" cells. If we assume that you have a <td> element, we:

1) give them a nice ID, e.g. row_0, row_1, etc...

2) write a function to iterate over them:

function updateRows(){
        $(this).html(index + 1); // add +1 to prevent 0 index.

I have written a jquery plugin which does exactly this, and you shouldnt need to "number" the rows per-se. All you need to do when deleting a row is to pass the index of the row being deleted.

eg, if you have a delete button in a row:

    <td> <input type="button" class="delete" value="delete this row" /></td>

The jQuery might look like

 var index = $(this).parents('tr').index();
 // tell your plugin to delete row "index"

The method from my plugin which does this looks something like:

removeRow: function (index) {
        return this.each(function () {
            var $this = $(this);
            var $tbody = $('tbody', $this);
            var $tr = $('tr', $tbody).eq(index);
            $this.trigger('rowRemoved', [$tr]);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.