Home > Software design >  Searchable drop down is not working using .append
Searchable drop down is not working using .append

Time:01-12

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 ><select  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"  id="add">
   Add Milestone
   </button>
</div>
<table>
   <tbody id="DynamicTable">
   </tbody>
</table>

CodePudding user response:

Hey my friend append after select2 function

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

CodePudding user response:

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 ><select  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.

  •  Tags:  
  • Related