JSFiddle - React, Tailwind, and code Playground

by wildanv10

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>
<section id="tags" class="row">
  <select class="chooser form-control" multiple="multiple">
    <option selected="selected">orange</option>
    <option selected="selected">white</option>
    <option>yellow</option>
    <option>blue</option>
    <option selected="selected">green</option>
    <option>purple</option>
    <option>red</option>
    <option selected="selected">grey</option>
    <option selected="selected">pink</option>
  </select>
  
  
  <select class="chooser form-control" multiple="multiple">
    <option selected="selected">orange</option>
    <option selected="selected">white</option>
    <option>yellow</option>
    <option>blue</option>
    <option selected="selected">green</option>
    <option>purple</option>
    <option>red</option>
    <option selected="selected">grey</option>
    <option selected="selected">pink</option>
  </select>
  <br>
  <button id="get-val-via-select2">check value via select2</button><br>
  <button id="get-val-via-dom">check value via dom</button>

  <table id="log"></table>
</section>

CSS

#log li {
    margin:5px;
}
table, td {
    border: 1px solid grey
    padding: 0;
}
table, button {
    min-width: 250px;
    margin-top: 15px;
}
.light {
    color: #999;
}

JavaScript

$(function() {
    
    // init select2
    $(".chooser").select2({
  		tags: true,
        width: 250
    })
    
    // init sortable
    $("ul.select2-selection__rendered").sortable({
        containment: 'parent'
    })
    
    // button #1 - get value from select2
    $('#get-val-via-select2').click(function(e){
      var v = $('.chooser').select2('val');
      $('#log').append('<tr><td class="light">select2 val:</td><td>'+v+'</td></tr>');
    });
    
    // button #2 - get value from dom
    $('#get-val-via-dom').click(function(e){
      var myVal = [];
      $('li.select2-selection__choice').each(function(index) {
        /* below we're getting the value from the 'title' attribute
        of the containing 'li'; might want to look and see if there's
        another bit of the dom you'd rather use like the actual text */
        var item = $( this ).attr('title');
        myVal.push(item);
      });
      $('#log').append('<tr><td class="light">value via dom:</td><td>'+myVal+'</td></tr>');
    });
    
});