Search code examples
javascriptjqueryindexingrow

Deleting table row and re-indexing the numbers


I have a difficulties about deleting and re-indexing the row counts.

For example, count numbers like 7 6 5 4 3 2 1. After deleting 3 I want them to be like 6 5 4 3 2 1. How can I do it?

function barcodeEntry(barcode) {
  if (barcode.length == 3) {
    var productCount = document.querySelectorAll('.barcodeNumber').length;
    var barcodeTable = document.getElementById("barcode_table");
    
    var rowHtml = "";
    rowHtml = '<tr>';

    if (productCount == 0) {
      rowHtml += '<td class="product-count text-right">' + 1 + '</td>'
    } else {
      productCount++;
      rowHtml += '<td class="product-count text-right">' + productCount + '</td>'
    }
    rowHtml += '<td class="barcodeNumber pl-5" >' + barcode + '</td>'
    rowHtml += '<td class="delete-btn">' + '<a class="mr-2 trash-btn"  >' + 'Delete' + '</a>' + '</td>'
    rowHtml += '</tr>';

    $("#barcode_table").prepend(rowHtml)
    
    $('.trash-btn').on('click', function() {
      $(this).closest("tr").remove();
    })
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js"></script>
<input id="barcodeInput" onkeyup="barcodeEntry(this.value)" />

<table class="w-100">
  <thead>
    <tr class="d-flex justify-content-around">
      <th>
        Count
      </th>
      <th class="pr-5">
        Barcode No
      </th>
      <th></th>
    </tr>
  </thead>
  <tbody id="barcode_table"></tbody>
</table>

jsFiddle link: https://jsfiddle.net/Aycan/8r7xd5us/1/

  • When I wrote numbers in input they are adding to table just as I wanted. Last count should be on the top. It is working like that in this example. But when I delete one td, count numbers also deleted but they are not descending. If count numbers 3 2 1 and I deleted 2, It shows me 3 1. What I want is if I delete td the others indexing again and excep 3 1 it should be 2 1.

Solution

  • Please use this code.

    ...
    
    $('.trash-btn').on('click', function() {
      $(this).closest("tr").remove();
      const rows = document.querySelectorAll(".product-count");
      [...rows].map((val, index) => {
        val.innerHTML = [...rows].length - index;
      });
    })
    
    ...