Search code examples
razorjquery-select2

Select2-Allow user to paste multiple values into dropdown from the existing dropdown data


I have a select2 implemented with data from server, and i need to let user paste multiple values to this select2 without allowing new values just the ones that already exist in dropdown.

javascript :

$(function() {
        //Initialize Select2 Elements
        $('.select2').select2({
            tags: true,
            tokenSeparators: [',', ', ', ' '],
            
        })

})

razor :

<div class="form-group">
@Html.ListBoxFor(m=>m.GroupUsersTo, (MultiSelectList)ViewBag.UserTypes, new {@class = "select2", multiple="multiple", data_placeholder="Groupe utilisateurs",style="width: 100%;" })
    
</div>

Solution

  • After having a good sleep i managed to understand the select2 better and i came with a solution based on the documentation https://select2.org/tagging. I customized the createTag function and test if the text pasted already exists or not if it doesn't exist than i prevent the creation of new tag.

    Code :

    $(function() {
            //Initialize Select2 Elements
            $('#UsersTo').select2({
    
                tokenSeparators: [',', ', ', ' '],
                tags: true,
                createTag: function(params) {
                  var length = $('#UsersTo option').filter(function() { 
                        return $(this).text() === params.term; 
                    }).length;
                  if (length == 0) {
                    // Return null to disable tag creation
                return null;
                }
    
                return {
                  id: params.term,
                  text: params.term
                }
            }
    
            })
            
    
        });