Clone table rows and change IDs of new rows in jQuery

You may try this (DEMO)

HTML:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
    <tr>
       <td>SelectOne</td>
       <td>Select two</td>
       <!-- More Headers -->
    </tr>
    <tr>
        <td>
            <select id="Id.0" name="Id.0">...</select>
        </td>
        <!-- More tds -->
        <td><input type="button" class="addButton" value="Add" /></td>
    </tr>
</table>

JS:

$(function(){
    $("#table-data").on('click', 'input.addButton', function() {
        var $tr = $(this).closest('tr');
        var allTrs = $tr.closest('table').find('tr');
        var lastTr = allTrs[allTrs.length-1];
        var $clone = $(lastTr).clone();
        $clone.find('td').each(function(){
            var el = $(this).find(':first-child');
            var id = el.attr('id') || null;
            if(id) {
                var i = id.substr(id.length-1);
                var prefix = id.substr(0, (id.length-1));
                el.attr('id', prefix+(+i+1));
                el.attr('name', prefix+(+i+1));
            }
        });
        $clone.find('input:text').val('');
        $tr.closest('table').append($clone);
    });

    $("#table-data").on('change', 'select', function(){
        var val = $(this).val();
        $(this).closest('tr').find('input:text').val(val);
    });
});

Tags:

Html

Jquery