Escuchen todos, para mi selección múltiple select2, me gustaría mostrar la cantidad de elementos seleccionados. El siguiente código indica esto:
Para un elemento seleccionado: "Seleccionado 1 de 2"
Para dos elementos seleccionados: "Seleccionado 2 de 2" "Seleccionado 2 de 2"
¿Alguien sabe cómo mostrar el texto una vez cuando ha seleccionado dos opciones?
<!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>cambié el código
return "Selected " + selected + " of " + total;a
if(selected==2){ return "Selected " + selected + " of " + total; }else{ return ""; //here you can return any other message }Eso da el resultado:
solo cambia esta línea:
return "Selected " + selected + " of " + total;a
if(selected==2){ return "Selected " + selected + " of " + total; }else{ return ""; //here you can return any other message }Puede editar esto para agregar más condiciones, como si el usuario selecciona> 2 opciones, si no ha seleccionado ninguna, etc.