John Leehey
John Leehey

Reputation: 22240

HTML table "Add Row" or "Remove Row" button column

I need a way to add or remove a row below another row in my html table. I'm using the dom, and can add and remove rows easily enough, but the problem comes up when I try to have a button column that adds and removes rows dynamically.

For example:

    |  Item Type  |     Item     |  Add/Remove Item
====================================================
    |   Fruit >   |     Apple    |   [ Add new ]
----------------------------------------------------
    |             |     Mango    |   [ Remove ]
----------------------------------------------------
    |             |     Pear     |   [ Remove ]
----------------------------------------------------

The [Add new] and [Remove] entries in the right column are buttons. Clicking a [Remove] button would delete the row (remove the pear or mango row). Clicking the [Add new] button would add a new Item (a new fruit).

If I specified the html for the button and added a new row based on an onClick, I can't think of a way to keep track of which row the button clicked from to add the new one. The best way I can think of is to have an array that keeps track of all the item types and what row they are on, then pass the id or name of the item into the method from onClick(), but this seems error-prone and messy.

To solve this, I'm willing to consider any solution (jquery plugin, javascript code, anything). Can someone point me to the best way to accomplish this?

Upvotes: 1

Views: 14992

Answers (1)

Cheery
Cheery

Reputation: 16214

Like this? I do not know where you are going to take values 'Mango' and 'Pear'.. http://jsfiddle.net/vPatQ/

$('.AddNew').click(function(){
   var row = $(this).closest('tr').clone();
   row.find('input').val('');
   $(this).closest('tr').after(row);
   $('input[type="button"]', row).removeClass('AddNew')
                                 .addClass('RemoveRow').val('Remove item');
});

$('table').on('click', '.RemoveRow', function(){
  $(this).closest('tr').remove();
});

for html code

<table>
    <tr><td>Item Type</td><td>Item</td><td>Add/Remove Item</td></tr>
    <tr><td><input type='text' value='Fruit >'></td>
        <td><input type='text' value='Apple'></td>
        <td><input type='button' class='AddNew' value='Add new item'></td></tr>
</table>

Upvotes: 3

Related Questions