3

I am simply creating a select list dynamically on a button click and appending it to a div. It is working without a problem but when I want this select list to behave like searchable as expected for select2 it is not working.

In below, I'm passing my select list into a method with an html helper named GGroupDropDownListForJavascript and the html result is like below.

 <select class="form-control input-xxlarge select2me" id="TagCategoryId" name="TagCategoryId">
 <option value="cf1d7da6-f49f-47aa-ba6d-a58f017c59ec">Element1</option>
 <option value="cf1d7da6-f49f-47aa-ba6d-a58f017c59ec">Element2</option>
 </select>

Here my Js code.

    $('#post').click(function (e) {
     var arrowBox = $( "<div>"+'@Ajax.JavaScriptStringEncode(Html.GGroupDropDownListForJavascript(p => p.TagCategoryId, Model.GroupedTagCategories, "").ToHtmlString())' + "</div>");
     arrowBox.appendTo($("#imageContainer"));
     $('#TagCategoryId').select2();
})

I m getting below error for this method.

Uncaught TypeError: $(...).select2 is not a function

I tested it for non-dynamically created elements btw and it is working without any problem. But when it comes to dynamically cretaed one it stops working. Am I missing something? Thank you.

revolver
  • 95
  • 1
  • 8

1 Answers1

2

I couldn't find a true way solution to my problem. Finally, i insert my GGroupDropDownListForJavascript to Html like below. And called it from my other div. It is not a great solution but solves the problem for me.

        <div id="copyDiv">
            @Html.GGroupDropDownListForJavascript(p => p.TagCategoryId, Model.GroupedTagCategories, "")
        </div>

and JS is like;

        var categoryBox = $('#copyDiv');
        categoryBox.appendTo(arrowBox);

UPDATE

Actually it doesn't work after i added above lines. It does only put the related select list into my div but my select list doesn't work anymore. So i solved my issue like below;

Execute below method; you have to be careful about 2 things here. First one is be sure to put a prefix "select" to your select2() selector otherwise you will get an "Uncaught query function not defined for Select2" error. This will solve that case and second one is make sure your select2.js is up to date.

   $('body').on('DOMNodeInserted', 'select', function () {
        $("select.form-select").select2();
    });
   $("button").on("click", function () {
         $(".dcontainer").append($('@Ajax.JavaScriptStringEncode(Html.GGroupDropDownListForJavascript(p => p.TagCategoryId, Model.GroupedTagCategories, "").ToHtmlString())'));
    });

i really hope this will help someone.

yanman1234
  • 1,009
  • 9
  • 27
revolver
  • 95
  • 1
  • 8