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

94
Vistas
Select2 templateSelection issue

Daear all, for my select2 multiselect, I would like to dispaly number of selected items. The code below state this:

For one selected item: "Selected 1 of 2"

For two selected items: "Selected 2 of 2" "Selected 2 of 2"

Does anybody know how to just display the text once when you have selected two options?

<!DOCTYPE html>
<html lang="en" >
<head>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css'> 
</head>
<body>
                                                                            
    <select id="idMulti" class="js-example-basic-multiple" style="width: 100%" multiple="multiple">
        <option value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option> 
    </select>   
</body>
          
<script src='https://code.jquery.com/jquery-3.5.1.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.js'></script>  


<script>
$(function() {

    $('#idMulti').select2({
      placeholder: '',
       minimumResultsForSearch: -1,
          templateSelection: function (data) {
            if (!data.id) { return data.text; }
            var selected = ($('#idMulti').val() || []).length;
            var total = $('option', $('#idMulti')).length;
            return "Selected " + selected + " of " + total;         
            }
    });
    
});
</script>

</html>

I changed the code

return "Selected " + selected + " of " + total;

to

if(selected==2){
    return "Selected " + selected + " of " + total;
}else{
    return ""; //here you can return any other message
}

That gives the result:

Result of the code above

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

just change this line:

return "Selected " + selected + " of " + total;

to

if(selected==2){
    return "Selected " + selected + " of " + total;
}else{
    return ""; //here you can return any other message
}

You can edit this if to add more conditions like if the user selects > 2 options, if it hasn't selected any and so on

about 4 years ago · Juan Pablo Isaza Denunciar
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