Search code examples
javascriptjqueryhtmlhtml-tableclone

Clone the first two text box values of a current row?


I have a requirement that for a table has the add row button and delete row button which I show in the following code.

For adding a row I want to clone the first two values "who" and "Location" of the current row to get the next row when I click on add row. In case I have different details on "who" and "Location" on third row when I click on "Add row" it has to take the same details of the third row and add the fourth row with the details of "who" and "location" in third row.

Hope you understand this scenario.

Html Table:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
    <tr>
        <td>Name</td>
        <td>Location</td>
        <td>From</td>
        <td>To</td>
        <td>Add</td>
    </tr>
    <tr class="tr_clone">
        <td><input type="text"  placeholder="who" name="who" /></td>
        <td><input type="text"  placeholder="location" name="location" /></td>
        <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"/></td>
        <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"/></td>
        <td><input type="button" name="add" value="Add" class="tr_clone_add"/></td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
    </tr>
</table><!-- /table#table-data -->

Jquery:

<script>
    $("input.tr_clone_add").live('click', function() {
        var $tr    = $(this).closest('.tr_clone');
        var $clone = $tr.clone();
        $clone.find(':text').val('');
        $tr.after($clone);
    });
    </script>

Javascript:

<script>
function deleteRow(r)
{
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("table-data").deleteRow(i);
}
</script>

Solution

  • Update: I had miss understood the question, since you need not require the dates, here is your answer and an update fiddle

    Code Snippet:

    $("input.tr_clone_add").live('click', function() {
        var $tr    = $(this).closest('.tr_clone');
        var $clone = $tr.clone();
        $clone.find('.datepicker').val('');
        $tr.after($clone);
    });