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:
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