lewis4u
lewis4u

Reputation: 15027

jQuery dynamic id rearange

I am trying to get a straight id numeration for table rows.

For example if you have a table with 5 rows the row ids should be from 1 - 5.

But because i have a dynamic table where a row can be added or deleted the problem comes when a user deletes a row somewhere in the middle.

Let's say you add 3 new rows into table

row-1
row-2
row-3

and if you delete second row you will end up with

row-1
row-3

and if you add a new row (because I am getting the id from previous row) you will get this

row-1
row-3
row-4

How to come around this problem? How to rearange the row ids dynamically?

I think this has to be bind with row deletion because adding is not a problem if no rows were deleted in the middle.

Here is an example at FIDDLE. inspect the id attributes in the web browser

Upvotes: 0

Views: 44

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to write the code to rearrange the ids of row from index 1. You can target rows from index 1 using gt selector along with .attr() callback function to set new ids:

$('#t1 tr:gt(0)').attr('id',function(i,o){
    return "r"+ i++ ;
});

Working Demo

Upvotes: 2

You can use the following:

var rows = $('#t1 tr') // get the amount of rows

$.each(rows, function(i, e) {
    $(e).attr("id", "r" + i);// set the new id
})

$(document).on('click', '#addRow', function() {
  var row = parseInt($('#t1 tr:last-child').attr('id').replace(/[^\d]/g, ''), 10) + 1;
  $('#t1').append('<tr id="r' + row + '"><td><input name="item[]" type="text"/></td><td><input name="quantity[]" type="number"/></td><td><button class="deleteRow">X</button></td></tr>');

  var rows = $('#t1 tr')

  $.each(rows, function(i, e) {
    $(e).attr("id", "r" + i);
  })
});

$(document).on('click', '.deleteRow', function() {
  var row = parseInt($(this).closest('tr').attr('id').replace(/[^\d]/g, ''), 10);

  if (row > 1) {
    $('#r' + row).remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
  <tr>
    <th>Item</th>
    <th>Quantity</th>
  </tr>
  <tr id="r1">
    <td>
      <input name="item[]" type="text" />
    </td>
    <td>
      <input name="quantity[]" type="number" />
    </td>
    <td>
      <button class="deleteRow">X</button>
    </td>
  </tr>
</table>
<button id="addRow">Add Row</button>

Upvotes: 1

Related Questions