简体   繁体   中英

How to limit number of displayed tags in select2?

I need to limit the number of displayed selected tags. Please notice that I do not want to restrict the maximum number of selected tags. So a user should be able to select as many options as he wants but I want to have control over how selected tags are displayed.

For example, I might want to just show a text like: 5 items are selected . I tried to use templateSelection config parameter but this function is called per selected option so I cannot return a single label for multiple selected options.

Also I found this answer but it's not working(setting the html inside change callback does not anything) and it seems more like a hack.

Is there some built-in or better way to achieve it?

In this example you can define after how many selected you want to show the text using the condition if (selected > 4) . Or remove that condition to have the text show for any input.

 $("#singleSelectExample").select2({ closeOnSelect: false }); $("#singleSelectExample2").select2(); $('#singleSelectExample').on('change', function() { var selected = $(this).val().length; var of = $(this).find('option').length; if (selected > 4) $(this).parent().find('.select2 .select2-selection ul').html('Selected ' + selected + ' of ' + of +' items.') });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script> <select id="singleSelectExample" multiple style="width: 300px;"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> <option value="7">Option 7</option> <option value="8">Option 8</option> <option value="9">Option 9</option> <option value="10">Option 10</option> </select>

最后,我找到了这篇关于适配器的很棒的文章,其中也包含了 jsfiddle。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM