Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different display value for selecte text using select2.js

Trying to implement a custom select dropdown using select2 plugin Is it possible to have the selected value to display only the actual option 'value' instead of the text, so if I selected 'Australian Dollar', the selected text should only display 'AUD'

My mark-up looks something like this:

<select name="convert-to" id="convert-to">
    <option value="AUD" data-currency="AUD">Australian Dollar</option>
    <option value="USD" selected="selected">US Dollar</option>
    <option value="JPY">Japanese Yen</option>
    <option value="EUR">Euro</option>
    <option value="GBP">British Pound</option>
    <option value="CAD">Canadian Dollar</option>
    <option value="HKD">Hong Kong Dollar</option>
</select>
like image 210
calebo Avatar asked May 06 '13 07:05

calebo


2 Answers

Simply use the formatSelection option. It provides the text and value of the selected option and sets the selection's text.

function formatSelection(val) {
  return val.id;
}

$('select').select2({
  formatSelection: formatSelection,
  width: 300
});

Fiddle

like image 84
netAction Avatar answered Sep 20 '22 18:09

netAction


The version 4 of Select 2 uses templateSelection instead of formatSelection:
https://select2.github.io/announcements-4.0.html#changed-templating
https://select2.github.io/options.html#templateSelection

$element.select2({
    /**
     * @param {Object} item
     * @param {Boolean} item.disabled
     * @param {HTMLOptionElement} item.element
     * @param {String} item.id
     * @param {Boolean} item.selected
     * @param {String} item.text
     * @returns {String}
     */
    templateSelection: function(item) {
        /** @type {jQuery} HTMLOptionElement */
        var $option = $(item.element);
        var $optGroup = $option.parent();
        return $optGroup.attr('label') + ' (' + item.text + ')';
    }
});
like image 32
Dmitry Fedyuk Avatar answered Sep 21 '22 18:09

Dmitry Fedyuk