title: jQuery select2 with WordPress
body: <p>I am working with jQuery <a href="https://select2.org" rel="nofollow noreferrer">select2</a> inside WordPress.</p>
  <p>I have a HTML table like this.</p>
  <p><a href="https://i.stack.imgur.com/T2uek.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T2uek.png" alt="enter image description here" /></a></p>
  <p>I need here if user clicks on <code>Bob SMith and admin</code> it will convert to a <code>select2</code> dropdown with multiple select.</p>
  <p>But when I click on it, it looks like below</p>
  <p><a href="https://i.stack.imgur.com/PGMHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PGMHd.png" alt="enter image description here" /></a></p>
  <p>and if I click again, the dropdown looks like this.</p>
  <p><a href="https://i.stack.imgur.com/UmQLt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UmQLt.png" alt="enter image description here" /></a></p>
  <p>When I click on any values, it looks like below</p>
  <p><a href="https://i.stack.imgur.com/beJlC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/beJlC.png" alt="enter image description here" /></a></p>
  <p>My jQuery code is like below</p>
  <pre><code>(function($) {
    var states = [];
    
    $(document).ready(function() {
      $(&quot;.volunteer&quot;).on(&quot;click&quot;, function(event) {
        // Check if select is already loaded
        if (!$(this).has(&quot;select&quot;).length) {
          var cellEle = $(this);
          var cellId = this.id;
  
          // Populate select element
          cellEle.html(`&lt;select class=&quot;js-example-basic-multiple&quot; multiple=&quot;multiple&quot;&gt;
              &lt;option value=&quot;AL&quot;&gt;Alabama&lt;/option&gt;
              &lt;option value=&quot;WY&quot;&gt;Wyoming&lt;/option&gt;
              &lt;/select&gt;`);
  
          // Initialise select2
          let selectEle = cellEle.children(&quot;select&quot;).select2();
          
          if(states[cellId]){
              // preselect existing value
            selectEle.val(states[cellId]);
            selectEle.trigger('change'); 
          }
  
          selectEle.on(&quot;select2:close&quot;, function(event) {
            // Get selected value
            selectedValue = selectEle.select2('data')[0]['text'];
  
            // Update array          
            states[cellId] = selectedValue.id;
            
            // Destroy select2
            selectEle.select2('destroy');
            
            // Change html to just show the value
            cellEle.html(selectedValue.id);
          });
        }
      });
    });
  })(jQuery)
  </code></pre>
  <p>My HTML code is like below</p>
  <pre><code>&lt;td class=&quot;volunteer&quot; id=&quot;47&quot;&gt;Bob SMith and admin&lt;/td&gt;
  </code></pre>