Create new tags

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. insertTag seems to fire on any key press also.

I think what I need is an event that is only fired when the user selects a tag, not as they are typing the tag.

Is there an event for this?

Here is my code:

          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. 

Everything works fine except the createTag.

You can use any of the change, change.select2, or select2:select events, all of which fire when a new tag becomes the selection (i.e., the user enters one of the tokenSeparator characters). In your event handler you can retrieve the current selection and then call your API to insert the tag’s value in your database. You’ll need to figure out how to distinguish a user-created tag from an item retrieved from your database (since selecting one of those items will also fire the events above). You can use the createTag callback to do that, by including an extra data value (e.g., newTag: true) in the Select2 data object you return to create the tag. Your change/select event handler can then look for that extra value to determine whether it needs to insert the tag into the database.

(Note: I agree that the createTag callback should only be called when the tag is actually selected, but apparently the creators of Select2 thought it should be called on each keystroke.)

1 Like