I am using Bootstrap to design my pages. I am following this page http://skote-light.node.themesbrand.com/form-advanced to create a Multiple Select.
<script src="~/assets/js/pages/form-advanced.init.js"></script> <div class="row mt-3"> <div class="col-lg-12"> <div class="form-group"> <label for="basicpill-firstname-input">Countries/Regions (You may add more countries/regions)</label> <select class="select2 form-control select2-multiple" multiple="multiple" data-placeholder="Choose ..."> <option value="SG">Singapore</option> <option value="CH">China</option> <option value="CA">California</option> </select> </div> </div> <div id="add-more">Add More<div>
The requirement is i need to have an add more button, to add more multiple select. So what I did is
$("#add-more").click(function () { $("#add-more").before( ` <div class="row mt-3"> <div class="col-lg-12"> <div class="form-group"> <label for="basicpill-firstname-input">Countries/Regions (You may add more countries/regions)</label> <select class="select2 form-control select2-multiple" multiple="multiple" data-placeholder="Choose ..."> <option value="SG">Singapore</option> <option value="CH">China</option> <option value="CA">California</option> </select> </div> </div> `
The problem is that when I am trying to append using JavaScript the multiple select behaves this way i.e. the bootstrap properties is not applied to it.
Most probably while appending using JavaScript, it is not able to use the JavaScript script.
Please help me to fix this issue. Thanks.
Advertisement
Answer
WORKING CODE
window.onload = function () { // no need to initialize here. //$('.select2-multiple').select2(); }); $("#add-more").click(function () { $("#add-more").before( ` <div class="row mt-3"> <div class="col-lg-12"> <div class="form-group"> <label for="basicpill-firstname-input">Countries/Regions (You may add more countries/regions)</label> <select class="select2 form-control select2-multiple" multiple="multiple" data-placeholder="Choose ..."> <option value="SG">Singapore</option> <option value="CH">China</option> <option value="CA">California</option> </select> </div> </div> `); //$('.select2-multiple:last').select2(); //initialize here instead $('.select2-multiple').select2(); });