motorscript.com

Selectize.js binding for Knockout.js

Published:

This is a custom binding for using Selectize.js with your Knockout.js powered application.

Selectize is an HTML select alternative (like Select2, Chosen). Knockout is an MVVM framework for Javascript.

This custom binding wraps the built-in options binding of Knockout.js. So, additional parameters like optionsValue, optionsText, optionsCaption, etc. can be used with this binding. See official documentation for further details. By default, the selectize binding uses id for optionsValue and name for optionsText.

By default, the text Choose... is used as optionsCaption. You can use optionsCaption: null for no captions (first item is selected by default).

The custom binding is available from https://gist.githubusercontent.com/xtranophilist/8001624/raw/ko_selectize.js

Example files are also available from https://gist.github.com/xtranophilist/8001624

Warning: This binding wraps the built-in options binding of Knockout.js and doesn't provide the whole object to Selectize and therefore options like searchField do not work out of the box.

1. Using selectize with plain select tag, with values built in view.

<select data-bind="selectize: {}">
    <option value="1">Val 1</option>
    <option value="2">Val 2</option>
</select>

2. Using values from observable array.

The dropdown is created with all objects from items observable array. The value of id or attribute set in optionsValue binding is set to item_id.

<select data-bind="selectize: items, value: item_id"></select>

3. Getting selected item as an object

The selectize binding provides optional object parameter. While the observable provided with value parameter (like item_id in our example) holds the id (or whatever property optionsValue defines), the observable provided with object parameter holds the whole item itself.

<select data-bind="selectize: items, value: my_item_id, object: my_item"></select>

4. Using with multiselect

<select data-bind="selectize: items, value: selected_items" multiple></select>

5. Passing additional options

See official Selectize.js usage documentation for all available options.

<select data-bind="selectize: items, value: selected_items2, options: {plugins: ['remove_button']}"
        multiple></select>