Search code examples
jqueryformshtml-tableexpand

Add new row of input elements and table rows using JQuery


I have the following code:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#add, .check ").click(function() {
            $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
            return false;
        });
    });
</script>

With the following in by body:

<form action='demo.php' method='post'>
 <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name[]" class='check' /></td>
    </tr>
    </tbody>
  </table>
  <input type='submit' />
</form>

How can I get it to clear the fields after adding them and maybe add an effect such as fade in or slide down, etc... Also, I would like it if any form element in the last row is focused it will add a new row automatically, but cannot figure out how to access the last row's form elements... :\


Solution

  • You can iterate through the new values with a find like so. Check out this fiddle

     $("#add, .check ").click(function() {
    $('#mytable tbody>tr:last')
        .clone(true)
        .insertAfter('#mytable tbody>tr:last').find('input').each(function(){
            $(this).val('');
        });
    });
    

    If you want to make the new row appear on focus of the last row, you'll have to delegate the focus on the first input of the last row. You want to use delegate because the rows are dynamically added. You can also add the fadein effect after you insert the cloned row. Here is a fiddle for this

    $("#mytable").delegate(' tbody>tr:last input:first','focus',function(){
        $('#mytable tbody>tr:last')
        .clone(true)
        .insertAfter('#mytable tbody>tr:last').hide().fadeIn().find('input').each(function(){
            $(this).val('');
        });
    });