Searchable drop down is not working using .append

Viewed 76

When i try to use searchable drop down it is not working in .append. But works perfectly fine normally.

$(document).ready(function(){
          $('#add').click(function(){
              var AllCount=$("#AllCount").val();
              $("#AllCount").val(parseInt(AllCount)+1)
              var finalCount= parseInt(AllCount)+1;       
              $('#DynamicTable').append(' <tr id="row'+finalCount+'"><td class="invoice-item"><select class="dropdown" id="employee_dropdown" name="state"><option value="AL">Alabama</option><option value="WY">Wyoming</option></select></td>');
          });
      });
   
   //jquery for show the dropdown
      $(document).ready(function() {
      $('.dropdown').select2();
   });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div>
   <button type="button" class="btn btn-success btn-sm m-1" id="add">
   Add Milestone
   </button>
</div>
<table>
   <tbody id="DynamicTable">
   </tbody>
</table>

2 Answers

You need to initialize select2 after each time you create or append a new select box.

$(document).ready(function(){
      $('#add').click(function(){
          var AllCount=$("#AllCount").val();
          $("#AllCount").val(parseInt(AllCount)+1)
          var finalCount= parseInt(AllCount)+1;       
          $('#DynamicTable').append(' <tr id="row'+finalCount+'"><td class="invoice-item"><select class="dropdown" name="state"><option value="AL">Alabama</option><option value="WY">Wyoming</option></select></td>');
      });
      $('#row'+finalCount).find('.dropdown').select2();
  });

Also same id employee_dropdown attribute for select was blocking initialization of multiple select2. You can remove the id attribute or use a distinct value for each element. I have removed id="employee_dropdown" for the select element above.

Hey my friend append after select2 function

$('#DynamicTable').append('...'); $('.dropdown').select2();

Related