dynamic add row table

 

 

HTML

<form id="personas" name="personas" method="post" action="">
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
    <tr>
      <td>Name</td>
      <td>Value</td>
      <td>Action</td>
    </tr>
    <tr class="person">
      <td>input</td>
      <td><input type="text" name="input-0"/></td>
      <td><a href="#" id="remove-item" ref="link-0">-</a></td>
    </tr>
  </table>
  <a href="#" id="add-item">+</a>
</form>

JS

<script type="text/javascript">
$(document).ready(function() {
    $("#add-item").click(function() {
      $('#mytable tr:last').clone(true).insertAfter('#mytable tr:last');
      var id = $('#mytable tr:last input').attr("name");
      var num_id = id.split("-")[1];
      var new_id = Number(num_id) + 1;
      $('#mytable tr:last [name]').attr('name','input-'+new_id);
      $('#mytable tr:last [ref]').attr('ref','link-'+new_id);
      $('#mytable tr:last [name]').val('');
      return false;
    });
    $("#remove-item").click(function() {
        var ref = $(this).attr('ref');
        var ref_num = ref.split("-")[1];
        if ( ref_num != 0 ){
            $(this).parent().parent().remove();
        }
        return false;
    });    
});
</script>