jianbing Ma jianbing Ma - 1 month ago 10
Ajax Question

select2 tags support, how to prohibit option to be a tag?

I use select2 with ajax search.How to set some option couldn't be selected.
for example,like the image below
enter image description here

I wrote a 'w' in the input, but the first line in the drop down is not the data come from ajax search. how to set it couldn't be selected or don't show it?

html code

<select id="normalSymptom" name="normalSymptom" class="form-control select2-multiple" multiple > </select>


javascript code

$('#normalSymptom').select2({
tags: true,
multiple: true,
tokenSeparators: [','],
minimumInputLength: 1,
minimumResultsForSearch: 10,
ajax: {
url: "/DiseaseSearch/symptomSearch",
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
word: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}

});

Answer

By default you are allowed to create new tags.

To disable tag creation, supply a createTag option. This option is a function that indicates whether a given tag is allowable. In your case, you want to allow no tags to be created, so return null, e.g.,

$('#normalSymptom').select2({
  tags: true,
  multiple: true,
  createTag: function (params) {
    return null;
  },
  // etc.
});

See JS Fiddle

Comments