Juan Pablo B
Juan Pablo B

Reputation: 525

Remove span from select2

I am using select2 which generates your selection and I have this, and I need to remove the 'x' from span:

enter image description here

This code prints the span element:

 for (let i = 0; i < valores.length; i++) {
     const option = new Option(valores[i]['nombre'], valores[i]['nombre'], true, valoresLocalStorage.includes(valores[i]['nombre']));
     valoresSelect.append(option).trigger('change');
 }

 valoresSelect.closest('[data-controller="fields--select"]').find('.select2-selection__choice').each(function () {
          console.log($(this).find('.select2-selection__choice__remove'));
          console.log('Span');

         $(this).find('.select2-selection__choice__remove').hide();
 });

In the chrome show me the console.log but does not hide it:

EVdn.k.fn.init [span.select2-selection__choice__remove, prevObject: EVdn.k.fn.init(1)] asociar:815 Span

Upvotes: 1

Views: 1255

Answers (1)

Swati
Swati

Reputation: 28522

You can use display: none !important; to hide close button inside select2 dropdown

Demo Code :

$("#somethings").select2();
$('#somethings').val(['1', '2']);
$('#somethings').trigger('change');
.select2-selection__choice__remove {
  display: none !important;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>


<select class="form-control2 select2" multiple="multiple" id="somethings">
  <option value="">-Selecr-</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>

</select>

Other way using jquery :

var valoresSelect = $("#somethings")
valoresSelect.select2()
//this is just for demo...
valoresSelect.val(['1', '2']);
valoresSelect.trigger('change');
remove_buttn();
//use this if you need to hide when user select other opitons..same do for https://select2.org/programmatic-control/events
valoresSelect.on('select2:select', function(e) {
  remove_buttn();
});

function remove_buttn() {
  //use next here
  valoresSelect.next().find('.select2-selection__choice').each(function() {
    $(this).find('.select2-selection__choice__remove').hide();
  });
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select class="form-control2 select2" multiple="multiple" id="somethings">
  <option value="">-Selecr-</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>

</select>

Upvotes: 2

Related Questions