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

268
Visualizações
Select2: How to add option dynamically when list is empty

I'm using select2 and have noticed that if there are not an option provided in the HTML (ignoring the blank one shown below to allow the placeholder to work), it won't let me dynamically add my own option. Typically, when there are other options it creates a tag and inserts it into the list of results.

I have templateResult and templateSelection to allow the display of the dropdown options with images on the left of their option text.

jQuery:

$('select').select2({
    placeholder: "Select or enter a {{ $itemType->itemTypeName }}",
    createTag: function (params) {
        return {
            id: params.term,
            text: params.term,
            newOption: true
        }
    },
    templateResult: function (option) {
        if(!option.id)
            return option.text;

        if(option.newOption) {
            $result.text(option.text);
            $result.append(" <em>(NEW)</em>");
        }
        else {
            var optimage = $(option.element).data('image'); 
            var $optItem = '<span>';
            if(optimage)
                $optItem += '<div style="display:inline-block; width:40px; text-align:center; margin-right:10px;"><img src="' + optimage + '" style="max-height:40px; max-width:40px; margin:0; vertical-align:middle;" /></div>';
            $optItem += $(option.element).text() + '</span>';

            $result = $($optItem);
        }
        return $result;
    },
    templateSelection: function (option) {
        if(!option.id) {
            return option.text;
        }
        var image = $(option.element).data('image');
        if(!image){
            return option.text;
        }
        else { 
            var $item = '<span>';
            $item += '<div style="display:inline-block; width:40px; text-align:center; margin-right:10px;"><img src="' + image + '" height="40px" style="margin:0; vertical-align:middle;" /></div>';
            $item += $(option.element).text() + '</span>';
            return $($item);
        }
    },
    tags: true,
    selectOnBlur: true,
    multiple: false
});

HTML:

<select id="itemID" name="itemID" required>
    <option></option>
</select>

If there are options that contain data inside the <select>, the jquery code creates a new tag, the templateResult function adds it to the list with "(NEW)" after it, and the user can select this newly created option as if it was there all along.

When there are no options with data in them, the templateResult function tries to execute $result.text(option.text); but it fails because there isn't a $result in existence yet.

How can I create $result when I try to add a new option?

about 4 years ago · Santiago Trujillo
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