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

192
Visualizações
Select2 js - How to create a option when typing on search box

I'm using select2 for create an unlimited option for select, which means whenever you type anything in select2 search box it can create an option related to what is the select for. Now I'm using the code below, which when type down it creates more than 1 option that I need it for.

Please help me with this.

$('#form-label-category-exterior').select2({
        matcher: function matchExterior(params, data){
          if ($.trim(params.term) === '') {
            return data;
          }
          if (typeof data.text === 'undefined') {
            return null;
          }
          if (data.text.indexOf(params.term) > -1) {
            var modifiedData = $.extend({}, data, true);
            return modifiedData;
          } else{
            var newOpt = new Option(params.term.toString() + '外装', params.term.toString() + '外装', true, true);
            $('#form-label-category-exterior').append(newOpt)
          }
          return null;
        }
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can see the source of this feature from the link below. But as far as i understand you can only add an extra option here. So i think this is not what you want.

Source Link

So i have different solution if you want to use. The code that i wrote it creates new option and delete old option that my code created. I tried to explain everything. I hope that you get the point.

$(document).ready(function() {
  let oldValue = "";
  $('#form-label-category-exterior').select2({
    matcher: function matchExterior(params, data){
      if ($.trim(params.term) === '') return data;
      if (typeof data.text === 'undefined') return null;
      if (data.text.indexOf(params.term) > -1) {
        return $.extend({}, data, true);
      } else {
        const newText = params.term.toString() + '外装';
        var newOpt = new Option(newText, newText);
        $(`#form-label-category-exterior option[value="${oldValue}"]`).remove()
        $('#form-label-category-exterior').append(newOpt)
        const $return = data.id == params.term.slice(0, -1) + '外装'
        oldValue = newText;
        $('#form-label-category-exterior').trigger('change');
        return $return ? {id: newText, text: newText } : null;
      }
      return null;
    }
  })
  $('#form-label-category-exterior').on('select2:closing', function (e) {
    oldValue = ""
  });
});
about 4 years ago · Juan Pablo Isaza Relatório
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