I am trying to clone a row which contains select2 tool ,when i clone that row using jQuery the cloned select2 is not responding.In image given below first select2 which is o
In the parent div don'nt apply select2 on it. First clone it and save it in a variable then apply select2. Later apply select2 on the origional(as the origional without select2 is alreay saved in a variable) and then apply on the newly created select. I tried this way and it is working
I've actually created account to answer this, since it took me a while to make it work.
This is not working when used before cloning:
$('.selectpicker').select2('destroy')
But this works in my case:
$('.selectpicker').select2('destroy');
$('.selectpicker')
.removeAttr('data-live-search')
.removeAttr('data-select2-id')
.removeAttr('aria-hidden')
.removeAttr('tabindex');
Just remove all the additional attributes which select2 adds.
Edit #1
Ok so seems like You also got to remove ID from the element that is being cloned since select2 tries to add it's own unique id when none is found on the select, but when You do have select it's getting messy and selet2 attaches only on the last element with the same ID.
I faced the same problem, while trying to add a row to a table dynamically. (the row contains more than one select2 instance.)
I solved it in this way:
function addrow()
{
var row = $("#table1 tr:last");
row.find(".select2").each(function(index)
{
$(this).select2('destroy');
});
var newrow = row.clone();
$("#table1").append(newrow);
$("select.select2").select2();
}
The trick was that you need to destroy all the instances of .select2 separately and before cloning the row. And then after cloning, re-initialize the .select2. I hope this will work for others as well.
How to use jorar91 code.
var $clone = $("#multiple_objects_with_select2").cloneSelect2();
$($clone ).find('select').select2({
width:'100%'
});
$("#some_place").append($clone);
I solved this problem with it:
Call destroy method before you add new row
$(".className").select2("destroy"); //Destroy method , connect with class no ID (recomend)
After it call select2 jQuery function:
$(".className").select2({
placeholder: "Example",
allowClear:true
});
hope it helps ;)
//Paste this code after your codes.
$('span.select2').remove();
$('select.select2').removeAttr('data-select2-id');
$('select.select2').select2();