skip to Main Content

i want to calculate the table rows, then assign to each tr in table id number based on the number of row,

i did the calculation like this var currentIndex = $('table tbody tr').length and i got the number of rows, then when i try to loop the rows, it change the id in all the rows with the same id, for example 1, i need to make it , for row number 1 id=1, row 2 = id=2 ..etc
` function generateId() {

        for (i = 0; i < $('table tbody tr').length; i++) {
            console.log('Hello World', + i -1);
            $('table  tbody tr td :input').attr('id', + i).attr('name', + i).prop('class', 'form-control form-control-sm form-control-solid formInput-' + i);
            //$('table tbody tr td :input').attr('name', + i);
            //$('#table tbody tr td :input').attr('class', 'form-control form-control-sm form-control-solid' + i);
        }

`

any ideas ??!!

2

Answers


  1. You can do it like this:

    $('table  tbody tr td :input').attr("id",function() {
      return "idprefix"+$('table  tbody tr td :input').index($(this));
    });
    

    Also it’s not recommended that id is a number.

    Demo

    $('table  tbody tr td :input').attr("id",function() {
      return "idprefix"+$('table  tbody tr td :input').index($(this));
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody>
        <tr>
          <td>
            <input />
          </td>
        </tr>
        <tr>
          <td>
            <input />
          </td>
        </tr>
        <tr>
          <td>
            <input />
          </td>
        </tr>
        <tr>
          <td>
            <input />
          </td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  2. To give id to each row based on number of rows. You can do it like this:-

    const rows = $('table tbody tr');
    for (i = 0; i < rows.length; i++) {
       let row = $(rows)[i];
       $(row).attr('id', i+1);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
        <thead>
          <th>#</th>
          <th>First Name</th>
        </thead>
        <tbody>
          <tr>
            <td>01</td>
            <td>John</td>
          </tr>
          <tr>
            <td>02</td>
            <td>John</td>
          </tr>
          <tr>
            <td>03</td>
            <td>John</td>
          </tr>
        </tbody>
      </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search