JQuery - select2 dropdown is disabled when cloning a table row

I have a table with four select2 dropdowns. When I clone a line to duplicate it, the drop-down lists of the new line are disabled, I canโ€™t click on them, what do I need to add to my code to activate them.

HTML table:

<table id="fla_inf" width="100%"> <tbody> <tr> <th class="tab_header" colspan="6">Flavors and Additives</th> </tr> <tr> <th class="tab_header_nam">Flavor Brand</th> <th class="tab_header_nam">Flavor Name</th> <th class="tab_header_nam">Dropper type</th> <th class="tab_header_nam">Quantity Unit</th> <th class="tab_header_nam">Quantity</th> <th class="tab_header_nam">Add/Remove row</th> </tr> <tr class="flavors"> <td>[brand_list]</td> <td><select id="arome0" class="select2-select"></select></td> <td><select id="dropper0" class="select2-select"> <option selected="selected" value="type1">type 1</option> <option value="type2">type 2-3</option> </select></td> <td><select id="qtyunit0" class="select2-select"> <option value="ml">ml</option> <option value="drops">drops</option> <option selected="selected" value="perc">%</option> </select></td> <td><input id="quantity0" class="quantity" type="number" /></td> <td><input class="addline" src="http://example.org/wp-content/uploads/2015/01/add.png" type="image" /><input class="remline" src="http://example.org/wp-content/uploads/2015/01/delete.png" type="image" /></td> </tr> </tbody> </table> 

and jquery code:

 // Add row to the table by cloning existing row $(document).on('click', '.addline', function(){ var $tr = $(this).closest('tr'); var allTrs = $tr.closest('table').find('tr'); var lastTr = allTrs[allTrs.length-1]; var $clone = $(lastTr).clone(); $clone.find('td').each(function(){ var el = $(this).find(':first-child'); var id = el.attr('id') || null; if(id) { var i = id.substr(id.length-1); var prefix = id.substr(0, (id.length-1)); el.attr('id', prefix+(+i+1)); el.attr('name', prefix+(+i+1)); } }); $tr.closest('tbody').append($clone); }); 
+5
source share
1 answer

I am trying to avoid cloning elements for this kind of reason. An alternative to cloning is to use a template for html.

If you want to continue cloning, you can turn off Select2 controls on the source line before cloning it, and then re-run them.

You will disable Select2 controls with the .select2('destroy') function.

 $(document).on('click', '.addline', function () { var $tr = $(this).closest('tr'); var $lastTr = $tr.closest('table').find('tr:last'); $lastTr.find('.select2-select').select2('destroy'); // Un-instrument original row var $clone = $lastTr.clone(); // Clone row $clone.find('td').each(function() { // Alter cloned ids // ... }); $tr.closest('tbody').append($clone); // Append clone $lastTr.find('.select2-select').select2(); // Re-instrument original row $clone.find('.select2-select').select2(); // Instrument clone }); 

jsfiddle

+8
source

Source: https://habr.com/ru/post/1213385/


All Articles