I have a table with four select2 dropdown lists. When I clone the row to duplicate it, the dropdown lists of the new row are disabled, I can't click on them, what do I have to add in my code in order to activate them.
The 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 the 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);
});
I try to avoid cloning elements for this kind of reason. An alternative to cloning is to use a template for the html.
If you want to continue cloning, you could un-instrument the Select2 controls in the original row before you clone it, and re-instrument them afterwards.
You un-instrument the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With