jQuery form repeater and select2 dont work togethe

2019-06-01 00:22发布

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.

7条回答
趁早两清
2楼-- · 2019-06-01 00:51

Hope this is not too late, this is working on my end. Had to manually 'destroy' select2 and remove all attached attributes to all select elements so as not to confuse the script and return the element in its 'original' state.

$('.repeater').repeater({
    show: function (){
        $(this).slideDown(function(){
            var selects = $('body').find('.pm-select2');
            $.each(selects, function(i, selectElement){
                $(selectElement).removeClass('select2-hidden-accessible').next('.select2-container').remove();
                $(selectElement).removeAttr('data-select2-id tabindex aria-hidden');
                initSelect2(selectElement);
            });
        });
    },
    hide: function (){
        $(this).slideUp();
    },
    isFirstItemUndeletable: true
});

function initSelect2(selectElement) {
    $(selectElement).select2({
        minimumResultsForSearch: Infinity
    });
}
查看更多
登录 后发表回答