Documentation for Select javascript module.

Files

app/scripts/modules/select.js

Select

Toggle javascript handles basic toggle function of 'default/active' states. It can be used for example to show/hide elements (with proper css), but it is also used for example in dropdown buttons. It toggles .active class on target element and also on itself.

Basic usage

Basic usage is show in forms-basic section of this styleguide.

Default initialization

Initialization is shown on example below. Constructor returns array of select DOM elements.

Basic initialization is done in main.js file for all selects with class .js-select.

Example:code
Code:
<script>
  var mySelects = new myApp.Select();
  /*
    console.log(mySelects);
    [select.js-select, select.js-select, ...]
   */
</script>

Custom initialization

In case it's needed to create select with more customized behavior, all Select2 options can be passed to myApp.Select constructor as second argument.

Code:
<select id="myCustomSelect">
  <option value="test">Test</option>
</select>
<script>
  // custom selector
  var customSelect = new myApp.Select({ selector: '#myCustomSelect' });

  // or add Select2 options
  var customSelectwithOptions = new myApp.Select(
    { selector: '#myCustomSelect' },
    {
      // ... Select2 options
    }
  );
</script>

Options

Custom defaults

Customized defaults of Select2.

Code:
const defaultOptions = {
  width: '100%',
  minimumResultsForSearch: Infinity,
  templateSelection: (state) => selectRenderTemplate(state, 'chip'),
  templateResult: (state) => selectRenderTemplate(state, 'option'),
  allowClear: $(item).attr('data-placeholder') && true,
  language: {
    maximumSelected: (state) => {
      switch ($(item).attr('data-lang')) {
        case 'en':
          return `You can only select ${state.maximum} items`;
        default:
          return `You can only select ${state.maximum} items`;
      }
    },
  },
};

DOM attributes

Available DOM attributes.

Name Type Default Description
data-placeholder string null Placeholder text.
If placeholder is set, select can be cleared via clear button ({ allowClear: true }).
data-selection-limit number null See Limit number of selections
data-select-search boolean false By default search in select options is turned off. Search can be enabled via this attribute.
...attributes See DOM attributes documention of Select2.

Methods

All Select2 methods are available. Example usage is shown below on example.

Code:
<select id="mySelect" class="js-select">
  <option value="test">Test</option>
</select>

<script>
  var mySelects = new myApp.Select();

  /*
    example of change event which should be called after manual dom change
    e.g. add option to select.
  */
  $('#mySelect').trigger('change');
  // or
  mySelects[0].trigger('change');

  // other Select2 methods such as .val(), .on(), etc.
</script>