Here's one approach to achieve that:
Using select2
's configuration options: templateResult, templateSelection and escapeMarkup, the dropdown list can be manipulated as per the requirements.
I'm using sample data here:
$('#example').select2({
data: [
{id: 'test1', text: 'January', subText: "Test1"},
{id: 'test2', text: 'February', subText: "Test2"},
{id: 'test3', text: 'March', subText: "Test3"}
],
placeholder: 'Select a month',
escapeMarkup: function (markup) {
return markup;
},
templateResult: function (d) {
return '<span>'+d.text+'</span><span class="pull-right subtext">'+d.subText+'</span>';
},
templateSelection: function (d) {
return d.text + ' ( ' + d.subText + ')';
}
}).val('test2').trigger('change');
.pull-right {
float: right!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<select id="example" multiple="multiple" style="width: 300px"></select>
Quick explanation:
templateSelection
is the way in which the list is rendered.
templateResult
is the manner in which the selection option is displayed (try selection an option and you'll see how it works)
escapeMarkup
, in short words, is to let select2 know that you're using HTML in the templateResult
and templateSelection
options.
- Applying
pull-right
(corresponding CSS: float: right;
to move the subtext to the right.
You can manipulate the options as per your requirement. I just wanted to show how it can be done. Hope this helps.