简体   繁体   中英

Select2 doesn't run on 'append'

Select2 function doesn't open on appending new select tag, and console has this error (Uncaught TypeError: $(...).select2 is not a function).

 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">   </script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js'></script>

$(document).on('click', '#addNewItem', function() {
      var a = $(".gh").val();
      a++;
      $('.asd').append('<select class="form-control select2" name="ProposalItemName[]">' +
        '<optgroup label="Items">' +
        '<option>test</option>' +
        '<option>test</option>' +
        '</optgroup>' +
        '</select>');
      $('.select2').select2();
    });

Here you go with a solution https://jsfiddle.net/cx5m40wu/2/

 $(document).on('click', '#addNewItem', function() { var a = $(".gh").val(); a++; $('.asd').append(`<select class="form-control select2" name="ProposalItemName[]"> <optgroup label="Items"> <option>test</option> <option>test</option> </optgroup> </select>`); $('.select2').select2(); }); 
 .alignRight{ float: right; padding-left: 15px; } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> <div class="asd"> test </div> <button id="addNewItem" type="button"> Click </button> 

I believe the issue in your code is 2 jQuery .

Check the order of JavaScript & CSS files.

I've used ES6 standard (template literals)

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM