Select2 Choice Box not working when dynamically load

1k Views Asked by At

Currently I a using Bootstrap Metronic theme and in that i am using Select2 Choice. This works when input type text used as "hidded". Syntax for it is

<input type="hidden" name="checks" class="input_tag form-control select2" value="" >

$(".input_tag").select2({
    tags: []
});

But when my input type text comes dynamically by jquery , as add new row functionality then i am not able to convert hidden type text boxes into select2 choice.

1

There are 1 best solutions below

0
On

You have to call the $(".input_tag").select2() function for that input after you create the dynamic content. JQuery doesn't detect newly created content to add plugins to it by default, you have to do this manually.

Here's an example:

HTML

<div id="test"></div>

JS

var myHTML = '<input type="hidden" name="checks" class="input_tag form-control select2" value="" >';

//I add the input dynamically
$("#test").html(myHTML).promise().done(
  function(){
    //I assign the select2 plugin AFTER dynamic content is added
    $(".input_tag").select2({
        tags: []
    });
  }
);

https://jsfiddle.net/p8zkhwmp/1/