javascript - Duplicating Div always duplicates -


to better understand question , see code visit fiddle: http://jsfiddle.net/dnyxc/

i have script (below) allows click icon , duplicates table allowing more inputs on included form. issue is, once click icon once duplicate it, anywhere click on table regardless of position duplicates table again.

document.getelementbyid('line-duplicate').onclick = duplicate;     var = 0;          function duplicate() {             var original = document.getelementbyid('item-table' + i);             var clone = original.clonenode(true); // "deep" clone             clone.id = "item-table" + ++i; // there can 1 element id             clone.onclick = duplicate; // event handlers not cloned             original.parentnode.appendchild(clone);         } 

here html table:

<table class="table" id="item-table0"> <tr>     <td>item name</td>     <td>qty/hrs</td>     <td>rate</td>     <td>tax rate</td>     <td>type</td>     <td>cost</td>     <td>actions</td> </tr> <tr>     <td>         <input class="input-medium" type="text" name="" />     </td>     <td>         <input class="input-mini" type="text" name="" placeholder="1" />     </td>     <td>         <input class="input-mini" type="text" name="" placeholder="0.00" />     </td>     <td></td>     <td>         <select class="input-small" name="">             <option>standard</option>             <option>expense</option>         </select>     </td>     <td>$0.00</td>     <td><i class="icon-plus" style="cursor:pointer;" id="line-duplicate"></i>  <i class="icon-trash pull-right"></i>         </a>     </td> </tr> 

endless duplication fine, issue when go type item form, duplicate table. need way duplicate table clicking plus icon.

to better understand question , see code visit fiddle: http://jsfiddle.net/dnyxc/

the issue binding onclick entire duplicated row duplicate() function.

you should make line-duplicate class (having multiple elements same id bad thing), , use document.getelementsbyclassname('line-duplicate') both inside , outside function bind duplicate function every single element class name, so:

document.getelementsbyclassname('line-duplicate')[0].onclick = duplicate;  var = 0;  function duplicate() {     var original = document.getelementbyid('item-table' + i);     var clone = original.clonenode(true); // "deep" clone     clone.id = "item-table" + ++i; // there can 1 element id     original.parentnode.appendchild(clone);     var listoflineduplicateitems = document.getelementsbyclassname('line-duplicate'); // must after table has been appended dom     (var j = 0; j < listoflineduplicateitems.length; ++j) {         listoflineduplicateitems[i].onclick = duplicate;     } } 

here's jsfiddle.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -