Select 2 version 4.0 allow user to enter free text

守給你的承諾、 提交于 2019-11-29 03:46:36

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 <select>.

<select class="required form-control" id="businessName" data-placeholder="Choose An Name" ></select>

The type attribute (previously set to hidden) is only required if you are using an <input /> and is not valid on a <select>. This shouldn't make any noticeable change to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!