Search code examples
htmlcssjquery-select2

How to right align some part of text in <option> in <select>


This is current look:

enter image description here

I expect this:

enter image description here

Code:

   <select class="form-control">
        <option value="1123x1">S\J [1123]</option>
        <option value="562x1">Rib / Int. [562]</option>
        <option value="1123x3">Fleece [1123]</option>
    </select>

Suggestion for select2 is also needed.


Solution

  • 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:

    1. templateSelection is the way in which the list is rendered.
    2. templateResult is the manner in which the selection option is displayed (try selection an option and you'll see how it works)
    3. escapeMarkup, in short words, is to let select2 know that you're using HTML in the templateResult and templateSelection options.
    4. 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.