Append table tr n times in jquery

I am trying to create dynamic tr inside the table based on function supplied (n) numbers.
but I don’t have an idea and am not able to make logic of how I do this. I am trying to make this whole today but the expected output not comes.
I want if I call newTR(5) then it will append 5 times tr in table > tbody also the serial number set with tr in id like; <tr id="${count+1}">

please help how me create this function in jQuery function and HTML

<table id="my_table">
   <tbody></tbody>
</table>
function newTR(number) {
  var count = 1;
  $("table#my_table > tbody").append(`
      <tr id="${count+1}">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
  `)
}

call to function: newTR(5)

expected output:

<table id="my_table">
   <body>
     <tr id="1">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
      <tr id="2">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
     <tr id="3">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
     <tr id="4">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
      <tr id="5">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
   </tbody>
</table>

You need a loop

function newTR(count) {
  for(let i=0; i < count; i++) {
     $("table#my_table > tbody").append(`
         <tr id="${i+1}">
              <td>1</td>
              <td>2</td>
              <td>3</td>
              <td>4</td>
         </tr>
     `)
   }
}
2 Likes

I was beaten to it :slight_smile: but I put it in a codepen anyway.

1 Like

thank you all

1 Like
function newTR(number) {
  $("#my_table > tbody").append(
    [...Array(number)].map(
      (_, i) => `
      <tr id="${i + 1}">
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
      </tr>
  `
    )
  );
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.