How to execute select2() function on dynamically created select list?

人盡茶涼 提交于 2019-12-10 20:54:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/34842944/how-to-execute-select2-function-on-dynamically-created-select-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!