delete select option onclick

Viewed 31

I am working with the following extension: https://select2.org

This is my code:

$('.phoneNumbers').select2({
  tags: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="phoneNumbers">
  <option value="1234">1234</option>
  <option value="5678">5678</option>
</select>

This is my result:

enter image description here

But now I would like to realize:

Each option should has a "delete icon". If I click on it, this option element should be deleted.

I can't found anything about this in the api documentation. Any idea?

1 Answers

Hmm, seems that is not trivial.

The select2 does not allow you to steal the click

I hacked the options here

$(document).on("click", ".delete", function(e) {
  const val = $(this).parent()[0].firstChild.textContent;
  $(".phoneNumbers").find("option[value=" + val + "]").remove()
  $('.phoneNumbers').select2("destroy")
  $('.phoneNumbers').select2({
    tags: true,
  })

})


$('.phoneNumbers').select2({
  tags: true,
})

$(".select2-selection__rendered").append("<span class='delete'>X</span>")

/* Select2 reset X 
$('.phoneNumbers').select2({
  tags: true,
  placeholder: 'Please select',
  allowClear: true
});

*/
select {
  width: 35%
}

span.delete {
  color: red;
  display: inline-block;
  float: right
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<select class="phoneNumbers">
  <option value="1234">1234</option>
  <option value="5678">5678</option>
</select>

Related