javascript - select2 from append not working - Stack Overflow

I'm using the select2 plugin from .I've got a form where I can add a new line. What I do is

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745378498a4625112.html

相关推荐

  • javascript - select2 from append not working - Stack Overflow

    I'm using the select2 plugin from .I've got a form where I can add a new line. What I do is

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信