0

i have tried many resources :

Cloned Select2 is not responding

select2 is not working

select2 is not working

Initialising select2 created dynamically

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

Select2 not displayed when added dynamically for the first time

Explanation:

View page is build up using Razor. i'm trying to clone the row using JQuery, first one is working properly and newly created( dynamic) is not opening (freezed). Image: image link

View Code:

                        <div id="ROW_0" class="template">
                            <hr />
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Credit Account</label>
                                        @Html.DropDownListFor(model => model.AccountsId, new SelectList(Model.Accountss, "Id", "Name"), "-- select account --", new { @class = "form-control select required select2insidemodal", @id = "creditAccount" })
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Amount</label>
                                        @Html.EditorFor(model => model.Credit, new { htmlAttributes = new { @class = "form-control", @type = "text", @id = "credit" } })
                                    </div>
                                    <span id="error-@Html.NameFor(vm => vm.Credit)" class="dN cR"></span>

                                </div>
                            </div>
                        </div>

Script:

//button for adding row 
$(document).ready(function () {

  $(document).on('click', "#addMore",function (e) {
             addNewRow();
         });
         
        function addNewRow() {
            var div = $(".template").clone().html();

            //find all select2 and destroy them   
           $(div).find(".select2").each(function (index) {
                if ($(this).data('select2')) {
                    $(this).select2('destroy');
                }
            });


           $("#dynamicBlock").prepend(div); //adding cloned data to new div '#dynamicBlock'.

Help me out.

Community
  • 1
  • 1

1 Answers1

0

It doesn't look like you are initialising the new select's after you have appended them to the page.

You will need to append new script to the page (and run it), to setup the select's, otherwise they will just sit there inert.

var initScript = '$(".select2insidemodal").select2();';

$('<script>' + initScript + '</' + 'script>').appendTo(document.body);

If you are going to clone more than one select, then I guess you could just add the init script last and only once, as it should init every cloned select.

Whiplash450
  • 943
  • 2
  • 12
  • 22