Select2:使用Ajax创建标签

问题描述 投票:0回答:1

我正在使用select2库。

我的select2元素可以通过ajax在数据库中搜索每个标签,并且效果很好。

我的问题是,我希望用户也能够创建一个新标签。查看他们的文档,我应该使用createTag选项。但是,这会在我单击该元素并在每次按键时触发。

任何人都可以提供有关如何实现目标的指导吗?

到目前为止是我的代码

I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.

Here is my code:

              $('.tags').select2({
              tags: true,
              placeholder: "These tags will apply to all lines",
              tokenSeparators: [','],
              ajax: {
                  url: '/api/tags/find',
                  dataType: 'json',
                  data: function (params) {
                      return {
                          q: $.trim(params.term)
                      };
                  },
                  processResults: function (data) {
                    return {
                        results: data
                    }
                  },
                  cache: true,
              },
              createTag: function(params) {
                  alert('tag created') // This is were I would put my ajax POST. 
              }
          });

javascript jquery-select2 jquery-select2-4
1个回答
0
投票

再次阅读文档后,我可以看到我应该一直使用事件https://select2.org/programmatic-control/events

我使用createTag选项将newTag: true分配给新创建的标签,并使用select2:selected事件检查是否选择了新标签,如果已选择,则向服务器发送ajax请求以创建该标签标签。


          $('.tags').select2({
              tags: true,
              placeholder: "These tags will apply to all lines",
              minimumInputLength: 3,
              tokenSeparators: [','],
              ajax: {
                  url: '/api/tags/find',
                  dataType: 'json',
                  data: function (params) {
                      return {
                          q: $.trim(params.term)
                      };
                  },
                  processResults: function (data) {
                    return {
                        results: data
                    }
                  },
                  // cache: true,
              },
              createTag: function(params) {
                  let term = $.trim(params.term);
                  if (term.length < 3)
                  {
                      return null
                  }

                  return {
                      id: term,
                      text: term,
                      newTag: true,
                  }
              },
          });

          $('.tags').on('select2:select', function (e) {
              let tag = e.params.data;
              if (tag.newTag === true)
              {
                  axios.post('/api/newtag', {
                      name: tag.text,
                      type: 'default',
                  })
              }
          });

© www.soinside.com 2019 - 2024. All rights reserved.