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: http://jsfiddle.net/LNXae/2/

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.

Answers:

Answer

http://jsfiddle.net/mblase75/LNXae/1/

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');
    $row.remove();

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

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(){
    $('[id*="row_"]').each(function(index){
        $(this).html(index + 1); // add +1 to prevent 0 index.
    };
};
Answer

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:

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

The jQuery might look like

$('.delete').click(function(){
 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]);
            $tr.remove();
        });
    }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.