Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing $(this) value returns undefined jquery

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?

like image 275
Azima Avatar asked Jan 26 '26 05:01

Azima


1 Answers

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

like image 52
Harun Yilmaz Avatar answered Jan 27 '26 17:01

Harun Yilmaz