views:

99

answers:

2

Could somebody suggest me a widget that can take an existing DOM object (like a table row) and clone it/add it to DOM after the existing original object and also allow to remove it or add others.

To explain myself better about what I want here is an example.

Lets say I have a table with one initial row (contains a number of empty fields). The widget would add a button on the side of the row which would allow to add a new row (by doubling the initial row with empty fields) or more and also it would add a remove button beside the added rows for the removal of the cloned rows except the original one (the first row).

I found a jQuery widget that does something like this called Multi Field Extender, but I have a number of issues with it on Internet Explorer that disables the widget. I tried to google it but I didn't find any alternative to it. Thank you in advance!

+1  A: 

Assuming your html is like this:

<tr>
  <td>
    <input type = "submit" class = "grow" value = "Add another row" />
  </td>
</tr>

Your jQuery to add a new row could be:

$("input.grow").live('click',function(){
  var $row = $(this).closest('tr');
  $row.clone(true).insertAfter($row);
});

Note: Untested, but the idea's sound.

Pickle
+1  A: 

Starting with something like this:

​<table>
  <tr>
    <td><input type="text" /></td>
    <td><input type="checkbox" /></td>
    <td><input type="button" class="addRow" value="Add" /></td>
  </tr>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

This jQuery would work for add/remove:

​$(​​​'table').delegate('​​​.addRow', 'click', function() {
  var r= $(this).closest('tr').clone(true);
  if(r.find('.removeRow').length === 0)
   r.append('<td><input type="button" class="removeRow" value="Remove" /></td>');
  r.insertAfter($(this).closest('tr'));
}).delegate('.removeRow', 'click', function() {
  $(this).closest('tr').remove();
});

You can see a quick demo here. This only depends on the add button being present, whatever is in the row will be copied, including current values in the inputs (and any event handlers, etc). If you need to manually add the Add button, then just add this on document.ready to create it:

$('table tr:first-child')
  .append('<td><input type="button" class="addRow" value="Add" /></td>');
​
Nick Craver
That's neat. It duplicates the values as well, which I think he was trying to avoid. There is probably a way to remove all values with around 70 characters added to the end of your code.
bradlis7
I didn't try to write a widget myself due to lack of time (I thougth that it would be a bigger issue than it is), but now I think I will do exactly that, as for the values (which are duplicated with the row) the solution is pretty simple. I can iterate over all the input elements and empty them before adding the row after the existing ones.
crazybyte