27
votes

I've been trying out the new Select2 v4.0 which has a lot of improvements. I'm mainly interested in the tags feature. I want to be able to search for tags via ajax and only be able to select a tag from the shown results and not be able to create new tags. The functionality is similar to StackOverflow - if you don't have the necessary reputation you can't create new tags, but you can still tag a question with existing tags.

Here's a jsfiddle with my code which is taken from the examples. In the example, you can create new tags which are what I want to limit. The user should be able to select tags only from the list that's retrieved from GitHub via ajax.

Does anybody know how to disable this functionality?

5

5 Answers

48
votes

This should work - in the initialization of select2, try returning undefined from the createTag function like so:

createTag: function(params) {
                return undefined;
           }
23
votes

I've been struggling with this as well, but got it working after a few hours.

I had specified a few token seperators (because my visitors are allowed to create tags in a different spot in the website). Turns out the seperators are still applied even if the tags configuration is set to false.

Solution: tags: false and do NOT add a value for tokenSeperators. Keep multiple: true.

7
votes

You can disable tags by removing tags: true when initializing Select2. Or alternatively, setting tags: false when initializing Select2. Tags are only enabled if the tags option is truthy, which it is when you are passing in true.

1
votes

I am not sure if I should add the following in here but as I was searching for the same issue google pointed me to this question. However I use an older version 3.x and this is how to achieve the same scenario for the 3.x versions.

Tested on version 3.5

createSearchChoice: function(params) {
    return undefined;
}
0
votes

tags:false,

$("#DropDownId").select2({
       minimumInputLength: 3,
       maximumSelectionLength: 10,
       tags: [],
       **tags:false,**
    ajax: {
        url: "@Url.Action("ActionName", "ControllerName")",
        type: "get",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                Title: params.term // search term
            };
        },
        processResults: function (response) {
            return {
                results: $.map(response, function (item) {
                    return {
                        text: item.Title,
                        id: item.NibafInstituteId
                    }
                })
            };
        }
    }
});