Is there a way to access select2 elements individually?

I want to grab all the select elements and check if they’re select with a multiple attribute or not. I want to do it like this but it doesn’t work.:

$('select').select2({
	//access each select element then check if the attribute multiple exists.
	closeOnSelect: $(this).attr('multiple') === null ? true : false,
})

This is probably not the right way to do it but should work.

$('select:not([multiple])').select2()
$('select[multiple]').select2({
	closeOnSelect: false
})

Hi @Chronzam, the reason why this doesn’t work is because this refers to the current execution context, which would be the global window in your snippet. To have it refer to the current select element, wrap the initialization in an each() callback:

// `this` refers to the global execution context here
$('select').each(function () {
  // `this` refers to the current select element now
  $(this).select2({
    closeOnSelect: this.multiple
  })
})
2 Likes

May I ask, why am I only getting an empty object when I do this $('select').each(()=>{}) and not $('select').each(function () {})?

This is because arrow functions explicitly have no this binding:

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.