I want to do something with Select2 like the templating example but I'm not using a predefined set of images so need to modify it somewhat.
I thought I could add the path to the image I want to display with a data attribute on each option and then instead of element.value I could use element.attr('data-thumb') but when I do that I get element.attr is not a function
HTML
<select>
<option value="A" data-thumb="a.jpg">A</option>
<option value="B" data-thumb="b.jpg">B</option>
<option value="C" data-thumb="c.jpg">C</option>
</select>
JS
function productStyles(selection) {
if (!selection.id) { return selection.text; }
var $selection = $(
'<img src="' + selection.element.attr('data-thumb')+ '"> ' + selection.text
);
return $selection;
};
$('.img-changer').select2({
templateResult: productStyles
});
Is it possible to access data attributes using .element or do I need another approach and if so, what would that be?