Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!