I have a database where I store Hex color codes. My goal is to achieve something like this (or similar): https://i.sstatic.net/2PbXj.png https://i.sstatic.net/3SNP0.png
It should function properly when selecting the values and after they are selected.
In a regular multiselect, I am able to do the following:
<div class="col-sm-10">
<select id="colors" name="colors[]" multiple class="form-control">
@foreach($colors as $key => $color)
<option value="{{$key}}" style="background-color:{{$color->code}}"></option>
@endforeach
</select>
</div>
However, when using the Select2 plugin, the styles get overridden. I attempted to add a span or div inside the select-option like this:
<option value="{{$key}}"><span style="background-color:{{$color->code}}"></span>{{$color->code}}</option>
Unfortunately, this approach also gets overwritten.
I came across this example in the documentation, but I'm unsure how to adapt it for use with Laravel
function formatState (state) {
if (!state.id) { return state.text; }
var $state = $(
'<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
);
return $state;
};
$(".js-example-templating").select2({
templateResult: formatState
});
Select 2 Version: 4.0.2