JSFiddle - React, Tailwind, and code Playground

by koh_edwin

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Select2 Test</title>
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
  </head>
  <body>
   

<select id="options">
  <option selected disabled>Select Option</option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
  <option value="5">Option 5</option>
  <option value="6">Option 6</option>
  <option value="7">Option 7</option>
</select>

<ul class="results">

</ul>

<button id="fetchValues">
  Fetch Values
</button>

<div id="values"></div>
  </body>
</html>

CSS

select{
  display: block;
}

ul.results{
  display: flex;
  width: 200px;
  margin-top: 1rem;
  overflow: auto;
  padding: 1rem;
  background-color: #fff;
  border: 1px solid #ddd;
  list-style-type: none;
}

ul.results li{
  margin-left: 0.5rem;
}

JavaScript

//initialize select2
 $('#options').select2();

//initialize a global array to store the selected options
let selectedOptionsArray = [];

//select2 event to capture the selected value
$('#options').on('select2:select', function(e) {
  let selectedOption = e.params.data;
  let optionIndex = selectedOption.element.index;
  let optionText = selectedOption.text;
  let optionValue = selectedOption.element.value;
  
  //check if option already exists in the array
  let index = selectedOptionsArray.indexOf(optionValue);
  if (index !== -1) {
    //do nothing if option exists
    return false;
  }
    
  //else, add the option value to the array
  selectedOptionsArray.push(optionValue);
  
  //append the option to the desired element
  $('ul.results').append(`<li>
            <button type="button" class="remove-option" data-value="${optionValue}" data-index="${optionIndex}" title="Remove item">
              <span aria-hidden="true">&times;</span> ${optionValue}
            </button>
          </li>`);
});


//click event listener on the appended to remove it
$(document).on('click', '.remove-option', function() {
    //remove the option from global array
  let findIndex = selectedOptionsArray.indexOf($(this).attr('data-value'));
  if (findIndex !== -1) {
    selectedOptionsArray.splice(findIndex, 1);
  }
  
  //remove the option element
  $(this).parent().remove();        //here, parent() refers to the li 
});

//fetch the current values
$('#fetchValues').click(function() {
  console.log(selectedOptionsArray);
  $('#values').html(selectedOptionsArray);
});