Nitish Nitish - 1 month ago 5
CSS Question

Table row cloning with select2 box creates another select box

I am trying to clone a table row , which contains a

select2
select box.

<table class="table" id="req_table">
<thead>
<tr>
<th class="col-md-2">Item</th>
<th class="col-md-2">Store Description</th>
<th class="col-md-2">Measurement Unit</th>
<th class="col-md-1">Quantity Demanded</th>
<th class="col-md-1">Rate</th>
<th class="col-md-1">Stock In Hand</th>
<th class="col-md-3">Remarks(If Any)</th>
</tr>
</thead>

<tbody>
<tr class="tr_clone">
<td class="col-md-2">{!! Form::select('item_measurement_id[]', $item_measurements, null, ['class' => 'select2 required col-md-12 item_measurement', 'id' => 'item_measurement_id', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
<td class="col-md-2">{!! Form::textarea('store_description[]', null, ['class' => 'form-control required', 'id' => 'store_description', 'cols' => 3, 'rows' => 2, 'placeholder' => 'Description of Stores', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
<td class="col-md-2">{!! Form::select('measurement_unit_id[]', $units, null, ['class' => 'required form-control col-md-12', 'id' => 'measurement_unit_id', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
<td class="col-md-1">{!! Form::number('quantity_demanded[]', null, ['class' => 'form-control required', 'id' => 'quantity_demanded', 'step' => '0.01', 'placeholder' => 'Quantity Demanded', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
<td class="col-md-1">{!! Form::number('rate[]', null, ['class' => 'rate form-control required', 'id' => 'rate', 'placeholder' => 'Rate', 'readonly' => true, 'step' => '0.01', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
<td class="col-md-1"><div class="col-md-3 stock_in_hand" style="margin-top:4px">0</div>
</td>
<td class="col-md-3">{!! Form::textarea('remarks[]', null, ['class' => 'form-control required', 'id' => 'remarks', 'rows' => 2, 'placeholder' => 'Remarks if any', 'autocomplete' => 'off',]) !!}</td>
</tr>
</tbody>
</table>


And the
javascript
is :

$('.add_more_item').click(function(e) {

$latest_tr = $('#req_table tr:last');
$clone = $latest_tr.clone();

$('select.select2').select2('destroy');
$latest_tr.after($clone);
$('select.select2').select2();
$clone.find(':text').val('');
item++;
show_hide_item(item);
})


When I clone the row, it creates another
select2
box , along with the select field. And this process continues when I click on add button. How do I remove the extra fields ?

Fiddle

Image sample

Answer

You run $('select.select2').select2('destroy'); after cloning row. Just move that line before $clone = $latest_tr.clone();:

$('select.select2').select2('destroy');

$clone = $latest_tr.clone();

Updated fiddle: https://jsfiddle.net/etgf979x/

Comments