Reading HTML5 data attributes from Select2 4.0
I have a selection defined like this:
<select class="myselect">
<option value="AL" data-foo="bar">Alabama</option>
...
<option value="WY" data-foo="biz">Wyoming</option>
</select>
In earlier versions of Select2, I can easily get the data-values like this:
alert($("#" + controlid).select2().find(":selected").data('foo'));
This however does not work in Select 2 4.0
Any ideas or suggestions?
source to share
Select2 4.0.0 works the same as the standard one <select>
, so the question is here: How to read the attributes data-*
on <option>
? ...
Now the answers in this question should work as they are if you just want to get the data attributes from an option that you can already get. It's important to note that Select2 does not directly set an attribute selected
, it sets a property selected
, so you must use a selector :selected
instead [selected]
if you want to get the selected options.
Your question is a bit broad, so you might be looking for a way to access these attributes using template functions. So your question is: How do I read attributes <option>
in template functions? which has an answer for Select2 3.5.x which still works in 4.0.0.
The first parameter of the templating function must be a data object. The data object, assuming you are not using AJAX (since <option>
it doesn't exist there), has a property element
that is the DOM element that the data object represents. You can get the data attribute from this by doing $(data.element).data("myAttribute")
like any other element.
source to share