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

277
Vistas
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?

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