Duplicate table line with Jquery incrementing ID's

461 views Asked by At

I have a table and need to duplicate lines and incrementing id of new lines created. I suppose all this can be done with JQUERY but don't this very well... Examples found stack overflow does not seem to work for me. thanks for your help

<table width="100%" id="table-data" >
  <tr>
    <td><strong>Title</strong></td>
    <td><input id="input_1" type="text" style="width:200px" value="Nom"/>
      <input type="text" style="width:200px" value="Prénom"/>
<a href="#"><i class="icon-plus"></i>ADD</a></td>
  </tr>

  <tr>
    <td valign="top"><strong>Title</strong></td>
    <td >
      <div id="bloc_cell">
        <input id="bloc_1" type="text" class="requis" value="Name"/>
        <br>
        <TEXTAREA class="requis"  name="positive3"   >Adress</TEXTAREA>
        <br>
        <input type="text"   value="Tél"/>
        <br>
        <input type="text"   value="Email"/>
        <br>
        <input type="text"   value="Web"/>
        </div>
      <a href="#"><i class="icon-plus">ADD</i></a></td>
  </tr>

  </table>     
1

There are 1 answers

0
AudioBubble On

Actually, i found a solution with this jsfiddle

But i just need to add a REMOVE button that remove the TR added. This remove button should only appears if from the second TR (first row can't be removed) Thanks for your help !

<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 id="id1" class="tr_clone">
        <td><input type="text" autofocus placeholder="who" name="who" id="who1" ></td>
        <td><select name="txtCategory[]" id="category1">
            <option value="">Please select</option>
        </select></td>
        <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker" id="datepicker_start1"></td>
        <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker" id="datepicker_end1"></td>
        <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
    </tr>
</table><!-- /table#table-data -->


var regex = /^(.*)(\d)+$/i;
var cindex = 1;

$("input.tr_clone_add").on('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var $clone = $tr.clone(true);
    cindex++;
        $clone.find(':text').val('');

    //update ids of elements in row
    $clone.find("*").each(function() {
            var id = this.id || "";
            var match = id.match(regex) || [];
            if (match.length == 3) {
                this.id = match[1] + (cindex);
            }
    });
    $tr.after($clone);
});