Initialize dynamically added select2

Viewed 2402

I've added select2 dynamically, but it won't initialize. I tried with following code (found on stackoverflow itself) but it wont work, please check my fiddle for code. Suggest me what I missed in code. Thanks in advance

Check this

function initializeSelect2(selectElementObj) {
    selectElementObj.select2({
        tags: true
    });
}

$(".select-to-select2").each(function() {
    initializeSelect2($(this));
});
1 Answers

Some issues with the example provided:

  • select2 was already being applied to all .select2 dropdowns without any options with this line: $('.select2').select2();
  • $(".select-to-select2").each does nothing, because there are no dropdowns with the class select-to-select2. (Also, there's no need for the each, you can just pass $(".select-to-select2") to initializeSelect2.)
  • The string being appended to wrapper was not valid HTML. That last "remove" link ought to be within the wrapping .row div.
  • ids must be unique to the page. After adding more of the same exact dropdowns, they had the same ID/names as previous ones, so this would cause unpredictable behavior (old dropdowns could lose their select2 and only the new ones would get it). E.g. you can't have more than one element with id="pgm_que_ans1", the next one has to be different.
  • in this call, initializeSelect2(wrapper), wrapper does not specify which dropdowns to apply select 2 on: , it's better to save the new HTML to a variable (e.g. var $newSelects('html here');, and once that is added to the DOM, pass only the .select2s within that to initializeSelect2, e.g. wrapper.append($newSelects); initializeSelect2($newSelects.find('.select2'))

Here's a demo with all that thrown together:

http://jsfiddle.net/qw3y821g/1/

Related