I am using the latest version of Select2: Select2 4.0.
I would like to allow users to enter free text. In other words if a user cannot find a option in the drop down
This was a change in 4.0.0 that resulted from undocumented behaviour in 3.x. In 3.x, if you were using createSearchChoice
you also should have been using tags
(setting it to true
or an empty array). This is because createSearchChoice
and tags
were tied together.
In 4.x, createSearchChoice
was renamed to createTag
because it was really creating the tag. This was documented in the 4.0.0-beta.2 release notes. Additionally, the second (also undocumented) parameter to createSearchChoice
was never implemented - but you don't actually need it in this case.
So, with those two changes noted, the working code to allow for new options to be added by the user is
$("#businessName").select2({
ajax: {
url: "/register/namelookup",
dataType: 'json',
delay: 250,
type: 'post',
data: function (params) {
return {
businessName: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 4,
tags: true
});
Notice that I did not implement createTag
, this is because the default implementation matched what your old createSearchChoice
was trying to do. I did add tags: true
though, because that is still required in order to make it work.
On top of that, you do have some invalid markup now that you have changed to a .
The type
attribute (previously set to hidden
) is only required if you are using an and is not valid on a
. This shouldn't make any noticeable change to you.