Adding "data-" attributes with select2

I am not sure what exactly you are asking but if you want to add data attribute you can do like this..

In Jquery:

$(element).attr('data-info', '222');

In javascript:

document.getElementById('elementId').setAttribute('data',"value: 'someValue'");

If your JSON response for ajax call looks like this:

[
  {
    "id": 1,
    "text": "option 1",
    "attr1": "custom attribute 1",
    "attr2": "custom attribute 2"
  },
  {
    "id": 2,
    "text": "option 2",
    "attr1": "custom attribute 3",
    "attr2": "custom attribute 4"
  }
]

Then, select2 seems to add them as data attributes for option automatically,

And this is how you can access them, example in change event:

$(element).on('change', function(e) {
  console.log($(this).select2('data')[0]);
})

In above example, you can now access your json response as select2('data') attribute. example: $(this).select2('data')[0].attr1 will return custom attribute 1

This way I was able to get data required data-attribute for selected option.


This solution applies to Select2 versions 4.0 or higher.

Assuming the attributes your talking about are loaded in the array you are returning in processResults. For example, if you are selecting a record like ('id':1,'text':'some-text','custom_attribute':'hello world')

Then on a change event you can do:

data=$("#selector").select2('data')[0];
console.log(data.custom_attribute);//displays hello world

Hope it helps..