I am using Select2 and jQuery form repeater (https://github.com/DubFriend/jquery.repeater)
I have searched on google/so for 2 days, but cant seem to get it to work.
include jquery/select2.js/jquery.repeater.js
var form = $('#form');
form.find('select').select2();
form.repeater({
show: function () {
$(this).show(function(){
form.find('select').select2('destroy').select2();
});
},
hide: function (remove) {
$(this).hide(remove);
}
});
The problem is the jQuery.repeater clones the div tag in which the input and select elements are when select2 is already initialized and has already changed the DOM, so jQuery.repeater copies the changed DOM. I tried to destroy select2 before the repeat action is called, but that dindt work either.
try this
Here is a solution which initializes select2 on form repeater button clock.
For an in depth overview of the problem and solution see here
If anyone else stumbles across this, I had the same problem in getting it to work and the solution is destroying the select2 and recreating.
I then had the issue that the select2 won't sit in the correct position when opened. For instance doing a repeat that results in a page scroll causes any select2 after the page scroll to then open in the position of the first.
To fix this (have the select2 open where it should (down the page)), set the dropdownParent to its immediate parent as so:
I solved it by first initializing the original select2 on document ready and then targeting with $this each instance of the repeated selected2 element on the repeater show method. For instance, if you have a simple select dropdown and a multiple select your code should look like this:
I'm working on a project where I use jQuery.repeater to repeat multiple select2 inputs. Following approach helped to solve my problem of initializing the inputs after they are loaded.
More exact jQuery selectors will help to only remove/initialize the selects you want to.
The CSS line I use always after initializing the select2 to adjust the width to the parent div/container.
Best regards
When using the
initEmpty: false
option, initialising select2 at the show function doesn't work for the first row. In this case you can also initialise select2 when the ready function runs.