0

At id column I need to add auto generated ID value dynamivcally when I added a new row

<table>
<tr>
    <th>Employee Id</th>
    <th>Employee Name</th>
    <th>Salary</th>
    <th>Email</th>              
</tr>
<tr>
   <td ></td>// for id
   <td><input type="text" id="new_name"></td>
   <td><input type="text" id="new_salary"></td>
   <td><input type="text" id="new_email"></td>
</tr>

</table>
Mahender Ambala
  • 363
  • 3
  • 18

1 Answers1

0

One possible solution is to declare a counter variable to keep track of how many rows have been generated. Then when you append a new row, you can set it's id attribute to this variable.

var index = 1;

$("#new-row").on("click", function() {
    var name = $("#new_name").val();
    var salary = $("#new_salary").val();
    var email = $("#new_email").val();
    $("table").html($("table").html() + 
                    "<tr id='row" + index + "'><td>" +
                    index + "<td>" + name + "</td><td>" +
                    salary + "</td><td>" +
                    email + "</td></tr>");
  index++;
});
#row1 { background: red; }

#row2 { background: orange; }
#row3 { background: yellow; }

td { text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
    <th>Employee Id</th>
    <th>Employee Name</th>
    <th>Salary</th>
    <th>Email</th>              
</tr>
<tr>
   <td ></td>// for id
   <td><input type="text" id="new_name"></td>
   <td><input type="text" id="new_salary"></td>
   <td><input type="text" id="new_email"></td>
</tr>

</table>

<button id="new-row">Generate new row</button>
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87