Vahn Vahn - 1 year ago 53
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 :


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

<table id="t_output" border="1">
<tr class="info">


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(){

and a fiddle :

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

Answer Source

Here's one approach:

function reCalculate() {
   $('#t_output tr:not(.info)>td:first-child').each(function(i) {

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.


function reCalculate() {
  $('#t_output tr:not(.info)').each(function(i) {

Here's the updated fiddle.