Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone table rows and change IDs of new rows in jQuery

Tags:

html

jquery

I have a table containing the following information:

<table id="Requirements">
    <tr>
        <td>
            <select id="Id.0" name="Id.0" onChange="changeTextBox();">...
        </td>
        <td>
            <select id="Comparator.0" name="Comparator.0" onChange="changeTextBox();">...
        </td>
        <td>
            <input type="text" id="Integer.0" name="Integer.0"/>...
        </td>
        <td>
            <select id="Value.0" name="Value.0">...
        </td>
    </tr>
</table>

and an add button.

<input type="button" id="addButton" value="Add" onClick="appendRow();"/>

I need the appendRow() function to not only clone the previous row, but change its id and name to Id.1, Id.2, Comparator.1, Comparator.2, etc. Because some of the drop down menus have so many values, it isn't feasible to create one giant append statement to recreate each row. How can I alter a clone's attributes upon creating it? Thanks!

Edit: The IDs must be in the .0, .1 format. This form posts to a URL that reads them as such

Edit 2: Code

function appendRow() {
    $("QualificationRequirements").append($("QualificationRequirements tr:last").clone());
}

No attempt to change IDs, just a simple clone function that I can't get to work.

like image 912
macklin Avatar asked Jul 30 '13 17:07

macklin


1 Answers

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);
    });
});
like image 70
The Alpha Avatar answered Oct 23 '22 06:10

The Alpha