3

I am trying to access $(this) inside the select2 initialization, but it returns undefined.

$(".tags").each(function() {
    var placeholder = "Select Email";
    if($(this).attr('name') === 'names[]')
        placeholder = "Select Name";
    $(this).select2({
        tags: true,
        placeholder: placeholder,
        language: {
            noResults: function () {
                return 'Type and enter to add new';
            },
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        createTag: function(params) {
            console.log($(this).attr('name')); // returns undefined
            if (params.term.indexOf('@') === -1)
                return null;
            return {
                id: params.term,
                text: params.term
            }
        }
    })
});

select2() is initialized for each .tags. I need to access $(this) inside the initialization here.

How can I do that?

Azima
  • 3,835
  • 15
  • 49
  • 95
  • 3
    https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback This might give you additional info – Tinu Jos K Jan 21 '20 at 11:28

2 Answers2

6

You can hold a reference to $(this) before calling select2()

$(".tags").each(function() {
    var placeholder = "Select Email";
    var $that = $(this);


    if($that.attr('name') === 'names[]')
        placeholder = "Select Name";
    $that.select2({
        tags: true,
        placeholder: placeholder,
        language: {
            noResults: function () {
                return 'Type and enter to add new';
            },
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        createTag: function(params) {
            console.log($that.attr('name'));
            if (params.term.indexOf('@') === -1)
                return null;
            return {
                id: params.term,
                text: params.term
            }
        }
    })
});

Hope this helps

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
4

The issue is because the createTag function does not run under the scope of the element which select2 was instantiated on.

To fix this you would need to retain a reference to the original element, which can be done by storing it in a variable in the each() handler:

$(".tags").each(function() {
  var $tag = $(this);

  // other logic...

  $tag.select2({
    // other logic...
    createTag: function(params) {
      console.log($tag.prop('name'));

      if (params.term.indexOf('@') === -1)
        return null;

      return {
        id: params.term,
        text: params.term
      }
    }
  })
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339