Dynamic option creating - Data attributes

Hi folks,

Is it possible to add data-* attributes when adding options dinamically?

I tried the following without success:

let data = {
   id: employees.values[i].CPF,
   text: employees.values[i].NOME + ' - ' + employees.values[i].FUNCAO,
   'data-email': employees.values[i].EMAIL
}

I also tried email instead of ‘data-email’.

You can add any properties you want (in addition to the defined id, text and disabled properties) to the data objects, but those properties are not reflected in the HTML <option> elements that Select2 generates. That shouldn’t be a problem if you only need to access the additional data properties from within your Select2 callbacks and event handlers; but if you need to access that data externally then you can’t do it via the <option> elements.

One solution might be to make sure the data array you’re using to populate the Select2 is available to other parts of your application. Then you could access the items in the data array directly, and get at the custom properties.

1 Like