Exploit
Exploit

Reputation: 6386

Clone table row limited up to two rows?

I am trying to dynamically add another row to my table but its only adding one row and wont add anymore.

Here is the html:

<table class="pretty property_units" style="width:800px;">
<thead>
<tr>
<th>Bedroom</th>
<th>Bathroom</th>
<th>Square Feet</th>
<th>Price</th>
<th>Available</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="rows">
    <td><input type='text' name='bedroom[]' class='input-small'></td>
    <td><input type='text' name='bath[]' class='input-small'></td>
    <td><input type='text' name='sqrt[]' class='input-small'></td>
    <td><input type='text' name='price[]' class='input-small'></td>
    <td>
        <select name='avail[]' class='input-small'>
        <option value='yes'>Yes</option>
        <option value='no'>No</option>
        </select>
    </td>
    <td><button class='btn btn-danger btn-small'>remove</button></td>
</tr>
</tbody>
</table>

Here is the js:

<script type="text/javascript">
$(document).ready(function() {
    var tblrow = $('table.property_units tr.rows:first-child').clone();
    $(".addrow").click(function() {
    $("table.property_units").append(tblrow);
    });
});
</script>

Notice how I'm not writing out the table row in append? I don't want to write it out, so please don't add that as a solution. It makes the code very messy.

Upvotes: 0

Views: 606

Answers (1)

Samuel Liew
Samuel Liew

Reputation: 79073

You are appending the row to the table, but you should be appending it to the <tbody>:

$("table.property_units tbody").append(tblrow);

Also, :first-child is an invalid selector. You meant to use :first:

$('table.property_units tr.rows:first').clone();

Also, move the clone INTO the click function:

$(".addrow").click(function() {
    var tblrow = $('table.property_units tr.rows:first').clone();
    $("table.property_units tbody").append(tblrow);
});

http://jsfiddle.net/2ygGt/4/

Upvotes: 1

Related Questions