简体   繁体   中英

Cloning Select2 with Jquery

I am having an issue with cloning a div with a select2 drop down.

When the first one is shown on the initial page load, the select2 works fine. When I click the button to clone it, the next select2 doesn't. It's like it's disabled and doesn't work.

My code is as follows;

<div class="input-main white_bg cloneneedsanalysis">
<div class="action-input clone-needs-analysis">
<div class="action-input-white-shorter">
<div class="inner-sub-title-less-padding">
<p>Audience Analysis</p>
</div>
<div class="col-md-12">
<div class="form-group">
<select class="select2 select2-multiple need_analysis_selector" multiple="multiple" data-placeholder="Choose ..." name="needs_analysis[]">
<option value="">-- Choose Audience Categories --</option>
<option value="536"> Finance -  - Cash collection</option>
<option value="537">IT -  - Comms IT</option>
<option value="538">Strategy -  - Strategy team 1</option>
</select>
</div>
</div>
</div>
<div class="action-input-plus-needs-analysis">
<a href="#" class="clone_needs_analysis_button">
<img src="http://www.test.com/assets/images/plus.jpg"></a>
</div>
<div class="action-input-remove-needs-analysis">
<a href="#" class="remove_needs_anaylsis_button">
<img src="http://www.test.com/assets/images/minus.jpg"></a>
</div>
</div>
</div>


$(document).on('click', '.clone_needs_analysis_button', function(e) {
    e.preventDefault();
    $(this).closest('.clone-needs-analysis').clone().insertAfter('.cloneneedsanalysis:last');
    $(this).closest('.action-input-plus').hide();
    $(this).closest('.action-input-remove').removeClass('hidden');
    $('.select2').select2();
});

Use $(this).closest('.clone-needs-analysis').clone(true, true) instead of $(this).closest('.clone-needs-analysis').clone() .

You need to specify the true, true parameters to tell JQuery to also clone the attached events.

Check the documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM