Initialising select2 created dynamically

前端 未结 6 1771
孤独总比滥情好
孤独总比滥情好 2020-12-01 04:49

I have a select2 drop-down for which I provide a matcher function. It is initialised like this on initial page load:

jQuery(document).ready(function() {
             


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 05:26

    I came across a similar situation recently but did it in a very usual way:

    $(document).ready(function() {
    
     //function to initialize select2
      function initializeSelect2(selectElementObj) {
        selectElementObj.select2({
          width: "80%",
          tags: true
        });
      }
    
    
     //onload: call the above function 
      $(".select-to-select2").each(function() {
        initializeSelect2($(this));
      });
    
     //dynamically added selects
    
      $(".add-new-select").on("click", function() {
        var newSelect = $("");
        $(".select-container").append(newSelect);
        initializeSelect2(newSelect);
      });
    
    
    });
    
    
    
    
    

    In case of the .load function find all the select elements which are to be initialized in the callback of load function and call initializeSelect2 on each of those select elements.

    I hope this helps someone who is looking for a simple solution.

提交回复
热议问题