Vahn Vahn - 5 months ago 14
Javascript Question

Fixing numbering in dynamic table

I have dynamic html table. When I press add button. A new row is appended to the table. Each row has a cancel button to remove itself.

The problem is after removing and adding a new row. the numbering is incorrect. The value in "Text column" also incorrect (not in proper order).

Here's my script :

html:

<input type="button" value="Add" id="btn_add" style="font-weight:bold" /><br />

<table id="t_output" border="1">
<tr class="info">
<td><strong>No</strong></td>
<td><strong>Text</strong></td>
<td><strong>Action</strong></td>
</tr>
</table>


jQuery:

$("#btn_add").click(function(){
var rowCount = $("#t_output tbody tr").length;

c_no = "<td>"+ rowCount +" </td>";
c_txt = "<td>TEXT"+(999-rowCount)+"</td>";
c_act = "<td align = 'middle'><input type='button' value='Cancel' id='del_btn' class='btn btn-danger' /></td>";

t_rows = "<tr>" + c_no + c_txt + c_act + "</tr>";
$("#t_output tbody").append(t_rows);
});

$('#t_output').on('click', '#del_btn', function(){
$(this).closest('tr').remove();
})


and a fiddle :https://jsfiddle.net/9fujvb21/

I prefer not to change the code too much if posibble. Thank you for your help

Answer

Here's one approach:

function reCalculate() {
   $('#t_output tr:not(.info)>td:first-child').each(function(i) {
      $(this).text(i+1);
   });
}

I wrote this function to calculate assign new numbers to all the rows when it is called. Now we simply call this function whenever we need to re calculate and assign numbers to the rows.

Here's the updated fiddle.


UPDATE

function reCalculate() {
  $('#t_output tr:not(.info)').each(function(i) {
    $(this).find('td:first-child').text(i+1).next().text('TEXT'+(999-i));
  });
}

Here's the updated fiddle.

Comments