Select2 4.0.0 works just like a standard <select>
, so the question here is: How do I read data-*
attributes on an <option>
?.
Now, the answers in that question should work as-is if you are just looking to get the data attributes from an option that you can already retrieve. It's important to note that Select2 doesn't directly set the selected
attribute, it sets the selected
property, so you must use the :selected
selector instead of [selected]
if you want to get the selected options.
Your question is a bit broad, so you might be looking for how to access these attributes with the templating functions. So your question there would be: How do I read the attributes of an <option>
in the templating functions?, which has an answer for Select2 3.5.x which still works in 4.0.0.
The first parameter to your templating function should be the data object. The data object, assuming you are not using AJAX (because the <option>
doesn't exist there), has a property element
which is the DOM element that the data object represents. You can get the data attribute off of these by doing $(data.element).data("myAttribute")
, just like you would with any other element.