Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
create new elements immediately in select2

I have a select2 that takes a few items, but I want to do a sort of slow loading of more items, by clicking the plus button. When the user hits the plus button, it will perform a new ajax that will add more options to select2. But the problem is that I haven't found any way to add new items to the select while it's open. I left as an example the append using an option.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.6/select2-bootstrap.min.css" rel="stylesheet" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="select-test" style="width: 300px"></select>
var formatTemplate, url = 'https://620aa88092946600171c5bf0.mockapi.io/test/v1/a';

formatTemplate = function(item) {
  var $state;

  if (item.id === 3) {
    $state = $('<span>Text: ' + item.text + '<button>+</button>' + '</span>');
  } else {
    $state = $('<span>Text: ' + item.text + '</span>');
  }

  return $state;
};

$('#select-test').select2({
  ajax: {
    url: url,
    type: 'GET',
    dataType: 'json',
    processResults: function(results) {
      return {
        results: results
      }
    },
  },
  templateResult: formatTemplate
});

async function asyncCheck() {
  await new Promise((resolve, reject) => {
    setTimeout(function() {
      $('li').on('mouseup', function(event) {
        var $button = $(this).find('button');

        if (event.target === $button[0]) {
          var newOption = new Option('Text: New', 9, false, false);

          event.stopPropagation();

          $('#select-test').append(newOption);
        }
      });

      $('.select2-dropdown--below').css('display', '');

      resolve();
    }, 700);
  });
}

$('#select-test').on('select2:open', function() {
  $('.select2-dropdown--below').css('display', 'none');
  asyncCheck();
});
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda