JSFiddle - React, Tailwind, and code Playground

by Timmy Willison

HTML

<form action="#" method="post">
    <input type="button" id="newItem" value="Add Row">
    <table id="items">
        <tr>
            <th>Item</th>
            <td>
                <input type="text" name="field1_row0">
            </td>
        </tr>
    </table>
</form>

JavaScript

var curItem = 0;
$("#newItem").click(function() {
    addItem($("#items"));
});

var addItem = function(elem) {
    curItem++;
    var lastRow = elem.find("tr:last");
    console.log( lastRow.find('input').attr('name') );
    var newRow = lastRow.clone();
    
    newRow.find("input").attr('name', function() {
        console.log( $(this).attr('name') );
        return $(this).attr('name').replace(/^(.*_row)\d+$/, '$1'
                                            + curItem);
    });

    lastRow.after(newRow);
    console.log( newRow.find('input').attr('name') );
    
    console.log( $('form').serialize() );
};