Dev01
Dev01

Reputation: 4222

Select2 Dynamic elements not reacting to event

I am using Select2 which works great. However I am using below code to create new dynamic select2 drop down but they do not react/open when clicking on them.

var relationshipcounter = 0;

$('#AddMoreRelationships').click(function () {
    var $relationship = $('.relationship'); // div containing select2 dropdown
    var $clone = $relationship.eq(0).clone();
    $clone[0].id = 'id_' + ++relationshipcounter;
    $relationship.eq(-1).after($clone);

    $relationship.find('select').trigger('change'); // not working
});

Screenshot:

enter image description here

JSFIDDLE:

http://jsfiddle.net/pHSdP/133/

Upvotes: 2

Views: 5661

Answers (5)

Sammaye
Sammaye

Reputation: 43884

I had this exact problem and, of course, the first thing I tried was a deep copy with data:

el.clone(true,true);

Which did not work. Instead the best method I found was:

el=other_el.clone()_etc; // cloning the old row
el.find('.select2-container').remove();
el.find('select').select2({width: 268});

el in both of these snippets is the div row that contains the select and so the Select2 element.

Essentially what I do in the second snippet is remove the "old" select2 which will always have the class of .select2-container and then recreate it on all found select elements within my new row.

Upvotes: 3

Dev01
Dev01

Reputation: 4222

Ok so issue is resolved, fiddle:

http://jsfiddle.net/WrSxV/1/

// add another select2
var counter = 0;
$('#addmore').click(function(){
    var $relationship = $('.relationship');
    var $clone = $("#RelationshipType").clone();
    $clone[0].id = 'id_' + ++counter;
    $clone.show();
    $relationship.eq(-1).after($clone);
    $clone.select2({ "width" : "200px" });// convert normal select to select2

    //$('body').select2().on('change', 'select', function(){
      //  alert(this.id);
    //}).trigger('change');

    return false;
});

Upvotes: 2

Deadlock
Deadlock

Reputation: 1577

Use .on to bind dynamically inserted elements to events like

$('body').on('click','#AddMoreRelationships',function () {
});

Upvotes: 0

Sergio
Sergio

Reputation: 6948

After cloning your object you have to reassign event for em:

var $clone = $relationship.eq(0).clone();
$clone.on("click", function_name);

Upvotes: 0

techfoobar
techfoobar

Reputation: 66688

You need to call clone with the true argument to copy over events and data as well. Otherwise only the element gets cloned, not the events that are bound to it.

$relationship.eq(0).clone(true);

Docs:http://api.jquery.com/clone/

Upvotes: 2

Related Questions