最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - select2 from append not working - Stack Overflow

programmeradmin1浏览0评论

I'm using the select2 plugin from /.

I've got a form where I can add a new line. What I do is get the html from the previous line and append it to my form.

So this worked and the select2 is also added to the new line. The problem is when I click on the select 2 element nothing happened.

Is there a way to solve this?

I'm using the select2 plugin from http://ivaynberg.github.io/select2/.

I've got a form where I can add a new line. What I do is get the html from the previous line and append it to my form.

So this worked and the select2 is also added to the new line. The problem is when I click on the select 2 element nothing happened.

Is there a way to solve this?

Share Improve this question asked Oct 1, 2013 at 16:05 Leon van der VeenLeon van der Veen 1,67212 gold badges42 silver badges62 bronze badges 3
  • Can you create jsfiddle for it? – Nikhil N Commented Oct 1, 2013 at 16:11
  • you might have to do some refreshing (destroy, then initial again) create a jsfiddle so we can help you – Sam Battat Commented Oct 1, 2013 at 16:20
  • jsfiddle/979nG/4 This is what I'm trying to do... – Leon van der Veen Commented Oct 2, 2013 at 7:01
Add a ment  | 

1 Answer 1

Reset to default 4

The reason it won't work the way you're doing it is because copying the HTML won't copy any event handlers or other select2 functionality.

To do that, as mentioned in the ments, we'll need to first destroy the original select2, clone its DOM elements, then reinitialise the original select2 and then initialise the copy.

It's probably easier to factor out the initialisation to a helper function, like so:

$(document).ready(function() {        

    var $selectParent = $('#select-parent'),
        $copy;

    init($selectParent);

    $("#duplicate").click(function() {

        $selectParent.select2('destroy');

        var $copy = $selectParent.clone();
        $(".form").append($copy);

        init($selectParent);
        init($copy);

    });
});

function init($elem) {
    $elem.select2({
        minimumResultsForSearch: -1,
        width: 'resolve'
    });   
}

Check this JSFiddle

发布评论

评论列表(0)

  1. 暂无评论