I have the below code which creates dynamic html table. The 4 rows get repeated
based on user's choice. The current code crates unique id for tr but i am interested in
giving unique id to td elements. Can someone please let me know how to achieve this.
<table id="master_table" border="0"> <tr> <th>COL1</th> <th>COL2</th> <th>COL3</th> <th>COL4</th> <td> </td> </tr> <tr> <td> <input type="text" name="col1" class="col1"/> </td> <td> <input type="text" name="col2" class="col2"/> </td> <td> <input type="text" name="col3" class="col3"/> </td> <td> <input type="text" name="col4" class="col4"/> </td> <td> <input type="button" name="addRow" class="add" value='Add'/> </td> <td> <input type="button" name="removeRow" class="removeRow" value='Delete'/> </td> </tr> <tr> <td colspan="4" align="center"> <input type="button" name="submit_data" class="submit" value="Submit" onclick="myFunction()"/> </td> </tr> </table>
$(document).ready(function () { $(document).on('click','#master_table .add',function () { var row=$(this).closest('tr'); var clone = row.clone(); var tr= clone.closest('tr'); tr.find('input[type=text]').val(''); $(this).closest('tr').after(clone); var $span=$("#master_table tr"); $span.attr('id',function (index) { return 'span' + index; }); }); $(document).on('click','#master_table .removeRow',function () { if ($('#master_table .add').length > 1) { $(this).closest('tr').remove(); } }); });
Working demo - http://jsfiddle.net/scriptonic/Vu8HC/1/