Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda