3 * Copyright (c) 2013 Brian Reavis & contributors
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under
10 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11 * ANY KIND, either express or implied. See the License for the specific language
12 * governing permissions and limitations under the License.
14 * @author Brian Reavis <brian@thirdroute.com>
17 (function(root, factory) {
18 if (typeof define === 'function' && define.amd) {
19 define('sifter', factory);
20 } else if (typeof exports === 'object') {
21 module.exports = factory();
23 root.Sifter = factory();
28 * Textually searches arrays and hashes of objects
29 * by property (or multiple properties). Designed
30 * specifically for autocomplete.
33 * @param {array|object} items
34 * @param {object} items
36 var Sifter = function(items, settings) {
38 this.settings = settings || {diacritics: true};
42 * Splits a search string into an array of individual
43 * regexps to be used to match results.
45 * @param {string} query
48 Sifter.prototype.tokenize = function(query) {
49 query = trim(String(query || '').toLowerCase());
50 if (!query || !query.length) return [];
52 var i, n, regex, letter;
54 var words = query.split(/ +/);
56 for (i = 0, n = words.length; i < n; i++) {
57 regex = escape_regex(words[i]);
58 if (this.settings.diacritics) {
59 for (letter in DIACRITICS) {
60 if (DIACRITICS.hasOwnProperty(letter)) {
61 regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
67 regex : new RegExp(regex, 'i')
75 * Iterates over arrays and hashes.
78 * this.iterator(this.items, function(item, id) {
79 * // invoked for each item
83 * @param {array|object} object
85 Sifter.prototype.iterator = function(object, callback) {
87 if (is_array(object)) {
88 iterator = Array.prototype.forEach || function(callback) {
89 for (var i = 0, n = this.length; i < n; i++) {
90 callback(this[i], i, this);
94 iterator = function(callback) {
95 for (var key in this) {
96 if (this.hasOwnProperty(key)) {
97 callback(this[key], key, this);
103 iterator.apply(object, [callback]);
107 * Returns a function to be used to score individual results.
109 * Good matches will have a higher score than poor matches.
110 * If an item is not a match, 0 will be returned by the function.
112 * @param {object|string} search
113 * @param {object} options (optional)
114 * @returns {function}
116 Sifter.prototype.getScoreFunction = function(search, options) {
117 var self, fields, tokens, token_count;
120 search = self.prepareSearch(search, options);
121 tokens = search.tokens;
122 fields = search.options.fields;
123 token_count = tokens.length;
126 * Calculates how close of a match the
127 * given value is against a search token.
129 * @param {mixed} value
130 * @param {object} token
133 var scoreValue = function(value, token) {
136 if (!value) return 0;
137 value = String(value || '');
138 pos = value.search(token.regex);
139 if (pos === -1) return 0;
140 score = token.string.length / value.length;
141 if (pos === 0) score += 0.5;
146 * Calculates the score of an object
147 * against the search query.
149 * @param {object} token
150 * @param {object} data
153 var scoreObject = (function() {
154 var field_count = fields.length;
156 return function() { return 0; };
158 if (field_count === 1) {
159 return function(token, data) {
160 return scoreValue(data[fields[0]], token);
163 return function(token, data) {
164 for (var i = 0, sum = 0; i < field_count; i++) {
165 sum += scoreValue(data[fields[i]], token);
167 return sum / field_count;
172 return function() { return 0; };
174 if (token_count === 1) {
175 return function(data) {
176 return scoreObject(tokens[0], data);
180 if (search.options.conjunction === 'and') {
181 return function(data) {
183 for (var i = 0, sum = 0; i < token_count; i++) {
184 score = scoreObject(tokens[i], data);
185 if (score <= 0) return 0;
188 return sum / token_count;
191 return function(data) {
192 for (var i = 0, sum = 0; i < token_count; i++) {
193 sum += scoreObject(tokens[i], data);
195 return sum / token_count;
201 * Returns a function that can be used to compare two
202 * results, for sorting purposes. If no sorting should
203 * be performed, `null` will be returned.
205 * @param {string|object} search
206 * @param {object} options
207 * @return function(a,b)
209 Sifter.prototype.getSortFunction = function(search, options) {
210 var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
213 search = self.prepareSearch(search, options);
214 sort = (!search.query && options.sort_empty) || options.sort;
217 * Fetches the specified sort field value
218 * from a search result item.
220 * @param {string} name
221 * @param {object} result
224 get_field = function(name, result) {
225 if (name === '$score') return result.score;
226 return self.items[result.id][name];
232 for (i = 0, n = sort.length; i < n; i++) {
233 if (search.query || sort[i].field !== '$score') {
234 fields.push(sort[i]);
239 // the "$score" field is implied to be the primary
240 // sort field, unless it's manually specified
242 implicit_score = true;
243 for (i = 0, n = fields.length; i < n; i++) {
244 if (fields[i].field === '$score') {
245 implicit_score = false;
249 if (implicit_score) {
250 fields.unshift({field: '$score', direction: 'desc'});
253 for (i = 0, n = fields.length; i < n; i++) {
254 if (fields[i].field === '$score') {
262 for (i = 0, n = fields.length; i < n; i++) {
263 multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
267 fields_count = fields.length;
270 } else if (fields_count === 1) {
271 field = fields[0].field;
272 multiplier = multipliers[0];
273 return function(a, b) {
274 return multiplier * cmp(
280 return function(a, b) {
281 var i, result, a_value, b_value, field;
282 for (i = 0; i < fields_count; i++) {
283 field = fields[i].field;
284 result = multipliers[i] * cmp(
288 if (result) return result;
296 * Parses a search query and returns an object
297 * with tokens and fields ready to be populated
300 * @param {string} query
301 * @param {object} options
304 Sifter.prototype.prepareSearch = function(query, options) {
305 if (typeof query === 'object') return query;
307 options = extend({}, options);
309 var option_fields = options.fields;
310 var option_sort = options.sort;
311 var option_sort_empty = options.sort_empty;
313 if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
314 if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
315 if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
319 query : String(query || '').toLowerCase(),
320 tokens : this.tokenize(query),
327 * Searches through all items and returns a sorted array of matches.
329 * The `options` parameter can contain:
331 * - fields {string|array}
337 * Returns an object containing:
345 * @param {string} query
346 * @param {object} options
349 Sifter.prototype.search = function(query, options) {
350 var self = this, value, score, search, calculateScore;
354 search = this.prepareSearch(query, options);
355 options = search.options;
356 query = search.query;
358 // generate result scoring function
359 fn_score = options.score || self.getScoreFunction(search);
361 // perform search and sort
363 self.iterator(self.items, function(item, id) {
364 score = fn_score(item);
365 if (options.filter === false || score > 0) {
366 search.items.push({'score': score, 'id': id});
370 self.iterator(self.items, function(item, id) {
371 search.items.push({'score': 1, 'id': id});
375 fn_sort = self.getSortFunction(search, options);
376 if (fn_sort) search.items.sort(fn_sort);
379 search.total = search.items.length;
380 if (typeof options.limit === 'number') {
381 search.items = search.items.slice(0, options.limit);
388 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
390 var cmp = function(a, b) {
391 if (typeof a === 'number' && typeof b === 'number') {
392 return a > b ? 1 : (a < b ? -1 : 0);
394 a = asciifold(String(a || ''));
395 b = asciifold(String(b || ''));
397 if (b > a) return -1;
401 var extend = function(a, b) {
403 for (i = 1, n = arguments.length; i < n; i++) {
404 object = arguments[i];
405 if (!object) continue;
407 if (object.hasOwnProperty(k)) {
415 var trim = function(str) {
416 return (str + '').replace(/^\s+|\s+$|/g, '');
419 var escape_regex = function(str) {
420 return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
423 var is_array = Array.isArray || ($ && $.isArray) || function(object) {
424 return Object.prototype.toString.call(object) === '[object Array]';
428 'a': '[aÀÁÂÃÄÅàáâãäåĀāąĄ]',
431 'e': '[eÈÉÊËèéêëěĚĒēęĘ]',
432 'i': '[iÌÍÎÏìíîïĪī]',
435 'o': '[oÒÓÔÕÕÖØòóôõöøŌō]',
439 'u': '[uÙÚÛÜùúûüůŮŪū]',
444 var asciifold = (function() {
446 var foreignletters = '';
448 for (k in DIACRITICS) {
449 if (DIACRITICS.hasOwnProperty(k)) {
450 chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
451 foreignletters += chunk;
452 for (i = 0, n = chunk.length; i < n; i++) {
453 lookup[chunk.charAt(i)] = k;
457 var regexp = new RegExp('[' + foreignletters + ']', 'g');
458 return function(str) {
459 return str.replace(regexp, function(foreignletter) {
460 return lookup[foreignletter];
467 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
476 * Copyright (c) 2013 Brian Reavis & contributors
478 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
479 * file except in compliance with the License. You may obtain a copy of the License at:
480 * http://www.apache.org/licenses/LICENSE-2.0
482 * Unless required by applicable law or agreed to in writing, software distributed under
483 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
484 * ANY KIND, either express or implied. See the License for the specific language
485 * governing permissions and limitations under the License.
487 * @author Brian Reavis <brian@thirdroute.com>
490 (function(root, factory) {
491 if (typeof define === 'function' && define.amd) {
492 define('microplugin', factory);
493 } else if (typeof exports === 'object') {
494 module.exports = factory();
496 root.MicroPlugin = factory();
499 var MicroPlugin = {};
501 MicroPlugin.mixin = function(Interface) {
502 Interface.plugins = {};
505 * Initializes the listed plugins (with options).
506 * Acceptable formats:
508 * List (without options):
511 * List (with options):
512 * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
514 * Hash (with options):
515 * {'a': { ... }, 'b': { ... }, 'c': { ... }}
517 * @param {mixed} plugins
519 Interface.prototype.initializePlugins = function(plugins) {
531 if (utils.isArray(plugins)) {
532 for (i = 0, n = plugins.length; i < n; i++) {
533 if (typeof plugins[i] === 'string') {
534 queue.push(plugins[i]);
536 self.plugins.settings[plugins[i].name] = plugins[i].options;
537 queue.push(plugins[i].name);
540 } else if (plugins) {
541 for (key in plugins) {
542 if (plugins.hasOwnProperty(key)) {
543 self.plugins.settings[key] = plugins[key];
549 while (queue.length) {
550 self.require(queue.shift());
554 Interface.prototype.loadPlugin = function(name) {
556 var plugins = self.plugins;
557 var plugin = Interface.plugins[name];
559 if (!Interface.plugins.hasOwnProperty(name)) {
560 throw new Error('Unable to find "' + name + '" plugin');
563 plugins.requested[name] = true;
564 plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
565 plugins.names.push(name);
569 * Initializes a plugin.
571 * @param {string} name
573 Interface.prototype.require = function(name) {
575 var plugins = self.plugins;
577 if (!self.plugins.loaded.hasOwnProperty(name)) {
578 if (plugins.requested[name]) {
579 throw new Error('Plugin has circular dependency ("' + name + '")');
581 self.loadPlugin(name);
584 return plugins.loaded[name];
588 * Registers a plugin.
590 * @param {string} name
591 * @param {function} fn
593 Interface.define = function(name, fn) {
594 Interface.plugins[name] = {
602 isArray: Array.isArray || function(vArg) {
603 return Object.prototype.toString.call(vArg) === '[object Array]';
611 * selectize.js (v0.12.0)
612 * Copyright (c) 2013–2015 Brian Reavis & contributors
614 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
615 * file except in compliance with the License. You may obtain a copy of the License at:
616 * http://www.apache.org/licenses/LICENSE-2.0
618 * Unless required by applicable law or agreed to in writing, software distributed under
619 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
620 * ANY KIND, either express or implied. See the License for the specific language
621 * governing permissions and limitations under the License.
623 * @author Brian Reavis <brian@thirdroute.com>
626 /*jshint curly:false */
627 /*jshint browser:true */
629 (function(root, factory) {
630 if (typeof define === 'function' && define.amd) {
631 define('selectize', ['jquery','sifter','microplugin'], factory);
632 } else if (typeof exports === 'object') {
633 module.exports = factory(require('jquery'), require('sifter'), require('microplugin'));
635 root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin);
637 }(this, function($, Sifter, MicroPlugin) {
640 var highlight = function($element, pattern) {
641 if (typeof pattern === 'string' && !pattern.length) return;
642 var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
644 var highlight = function(node) {
646 if (node.nodeType === 3) {
647 var pos = node.data.search(regex);
648 if (pos >= 0 && node.data.length > 0) {
649 var match = node.data.match(regex);
650 var spannode = document.createElement('span');
651 spannode.className = 'highlight';
652 var middlebit = node.splitText(pos);
653 var endbit = middlebit.splitText(match[0].length);
654 var middleclone = middlebit.cloneNode(true);
655 spannode.appendChild(middleclone);
656 middlebit.parentNode.replaceChild(spannode, middlebit);
659 } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
660 for (var i = 0; i < node.childNodes.length; ++i) {
661 i += highlight(node.childNodes[i]);
667 return $element.each(function() {
672 var MicroEvent = function() {};
673 MicroEvent.prototype = {
674 on: function(event, fct){
675 this._events = this._events || {};
676 this._events[event] = this._events[event] || [];
677 this._events[event].push(fct);
679 off: function(event, fct){
680 var n = arguments.length;
681 if (n === 0) return delete this._events;
682 if (n === 1) return delete this._events[event];
684 this._events = this._events || {};
685 if (event in this._events === false) return;
686 this._events[event].splice(this._events[event].indexOf(fct), 1);
688 trigger: function(event /* , args... */){
689 this._events = this._events || {};
690 if (event in this._events === false) return;
691 for (var i = 0; i < this._events[event].length; i++){
692 this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
698 * Mixin will delegate all MicroEvent.js function in the destination object.
700 * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
702 * @param {object} the object which will support MicroEvent
704 MicroEvent.mixin = function(destObject){
705 var props = ['on', 'off', 'trigger'];
706 for (var i = 0; i < props.length; i++){
707 destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
711 var IS_MAC = /Mac/.test(navigator.userAgent);
723 var KEY_BACKSPACE = 8;
726 var KEY_CMD = IS_MAC ? 91 : 17;
727 var KEY_CTRL = IS_MAC ? 18 : 17;
733 // for now, android support in general is too spotty to support validity
734 var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('form').validity;
736 var isset = function(object) {
737 return typeof object !== 'undefined';
741 * Converts a scalar to its best string representation
742 * for hash keys and HTML attribute values.
753 * @param {string} value
754 * @returns {string|null}
756 var hash_key = function(value) {
757 if (typeof value === 'undefined' || value === null) return null;
758 if (typeof value === 'boolean') return value ? '1' : '0';
763 * Escapes a string for use within HTML.
765 * @param {string} str
768 var escape_html = function(str) {
770 .replace(/&/g, '&')
771 .replace(/</g, '<')
772 .replace(/>/g, '>')
773 .replace(/"/g, '"');
777 * Escapes "$" characters in replacement strings.
779 * @param {string} str
782 var escape_replace = function(str) {
783 return (str + '').replace(/\$/g, '$$$$');
789 * Wraps `method` on `self` so that `fn`
790 * is invoked before the original method.
792 * @param {object} self
793 * @param {string} method
794 * @param {function} fn
796 hook.before = function(self, method, fn) {
797 var original = self[method];
798 self[method] = function() {
799 fn.apply(self, arguments);
800 return original.apply(self, arguments);
805 * Wraps `method` on `self` so that `fn`
806 * is invoked after the original method.
808 * @param {object} self
809 * @param {string} method
810 * @param {function} fn
812 hook.after = function(self, method, fn) {
813 var original = self[method];
814 self[method] = function() {
815 var result = original.apply(self, arguments);
816 fn.apply(self, arguments);
822 * Wraps `fn` so that it can only be invoked once.
824 * @param {function} fn
825 * @returns {function}
827 var once = function(fn) {
832 fn.apply(this, arguments);
837 * Wraps `fn` so that it can only be called once
838 * every `delay` milliseconds (invoked on the falling edge).
840 * @param {function} fn
842 * @returns {function}
844 var debounce = function(fn, delay) {
848 var args = arguments;
849 window.clearTimeout(timeout);
850 timeout = window.setTimeout(function() {
851 fn.apply(self, args);
857 * Debounce all fired events types listed in `types`
858 * while executing the provided `fn`.
860 * @param {object} self
861 * @param {array} types
862 * @param {function} fn
864 var debounce_events = function(self, types, fn) {
866 var trigger = self.trigger;
869 // override trigger method
870 self.trigger = function() {
871 var type = arguments[0];
872 if (types.indexOf(type) !== -1) {
873 event_args[type] = arguments;
875 return trigger.apply(self, arguments);
879 // invoke provided function
881 self.trigger = trigger;
883 // trigger queued events
884 for (type in event_args) {
885 if (event_args.hasOwnProperty(type)) {
886 trigger.apply(self, event_args[type]);
892 * A workaround for http://bugs.jquery.com/ticket/6696
894 * @param {object} $parent - Parent element to listen on.
895 * @param {string} event - Event name.
896 * @param {string} selector - Descendant selector to filter by.
897 * @param {function} fn - Event handler.
899 var watchChildEvent = function($parent, event, selector, fn) {
900 $parent.on(event, selector, function(e) {
901 var child = e.target;
902 while (child && child.parentNode !== $parent[0]) {
903 child = child.parentNode;
905 e.currentTarget = child;
906 return fn.apply(this, [e]);
911 * Determines the current selection within a text input control.
912 * Returns an object containing:
916 * @param {object} input
919 var getSelection = function(input) {
921 if ('selectionStart' in input) {
922 result.start = input.selectionStart;
923 result.length = input.selectionEnd - result.start;
924 } else if (document.selection) {
926 var sel = document.selection.createRange();
927 var selLen = document.selection.createRange().text.length;
928 sel.moveStart('character', -input.value.length);
929 result.start = sel.text.length - selLen;
930 result.length = selLen;
936 * Copies CSS properties from one element to another.
938 * @param {object} $from
939 * @param {object} $to
940 * @param {array} properties
942 var transferStyles = function($from, $to, properties) {
943 var i, n, styles = {};
945 for (i = 0, n = properties.length; i < n; i++) {
946 styles[properties[i]] = $from.css(properties[i]);
949 styles = $from.css();
955 * Measures the width of a string within a
956 * parent element (in pixels).
958 * @param {string} str
959 * @param {object} $parent
962 var measureString = function(str, $parent) {
967 var $test = $('<test>').css({
968 position: 'absolute',
974 }).text(str).appendTo('body');
976 transferStyles($parent, $test, [
984 var width = $test.width();
991 * Sets up an input to grow horizontally as the user
992 * types. If the value is changed manually, you can
993 * trigger the "update" handler to resize:
995 * $input.trigger('update');
997 * @param {object} $input
999 var autoGrow = function($input) {
1000 var currentWidth = null;
1002 var update = function(e, options) {
1003 var value, keyCode, printable, placeholder, width;
1004 var shift, character, selection;
1005 e = e || window.event || {};
1006 options = options || {};
1008 if (e.metaKey || e.altKey) return;
1009 if (!options.force && $input.data('grow') === false) return;
1011 value = $input.val();
1012 if (e.type && e.type.toLowerCase() === 'keydown') {
1013 keyCode = e.keyCode;
1015 (keyCode >= 97 && keyCode <= 122) || // a-z
1016 (keyCode >= 65 && keyCode <= 90) || // A-Z
1017 (keyCode >= 48 && keyCode <= 57) || // 0-9
1018 keyCode === 32 // space
1021 if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
1022 selection = getSelection($input[0]);
1023 if (selection.length) {
1024 value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
1025 } else if (keyCode === KEY_BACKSPACE && selection.start) {
1026 value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
1027 } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
1028 value = value.substring(0, selection.start) + value.substring(selection.start + 1);
1030 } else if (printable) {
1032 character = String.fromCharCode(e.keyCode);
1033 if (shift) character = character.toUpperCase();
1034 else character = character.toLowerCase();
1039 placeholder = $input.attr('placeholder');
1040 if (!value && placeholder) {
1041 value = placeholder;
1044 width = measureString(value, $input) + 4;
1045 if (width !== currentWidth) {
1046 currentWidth = width;
1047 $input.width(width);
1048 $input.triggerHandler('resize');
1052 $input.on('keydown keyup update blur', update);
1056 var Selectize = function($input, settings) {
1057 var key, i, n, dir, input, self = this;
1059 input.selectize = self;
1061 // detect rtl environment
1062 var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
1063 dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
1064 dir = dir || $input.parents('[dir]:first').attr('dir') || '';
1066 // setup default state
1069 settings : settings,
1071 tabIndex : $input.attr('tabindex') || '',
1072 tagType : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
1073 rtl : /rtl/i.test(dir),
1075 eventNS : '.selectize' + (++Selectize.count),
1076 highlightedValue : null,
1079 isRequired : $input.is('[required]'),
1083 isInputHidden : false,
1085 isShiftDown : false,
1088 ignoreFocus : false,
1090 ignoreHover : false,
1092 currentResults : null,
1096 loadedSearches : {},
1098 $activeOption : null,
1106 onSearchChange : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
1110 self.sifter = new Sifter(this.options, {diacritics: settings.diacritics});
1112 // build options table
1113 if (self.settings.options) {
1114 for (i = 0, n = self.settings.options.length; i < n; i++) {
1115 self.registerOption(self.settings.options[i]);
1117 delete self.settings.options;
1120 // build optgroup table
1121 if (self.settings.optgroups) {
1122 for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
1123 self.registerOptionGroup(self.settings.optgroups[i]);
1125 delete self.settings.optgroups;
1128 // option-dependent defaults
1129 self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
1130 if (typeof self.settings.hideSelected !== 'boolean') {
1131 self.settings.hideSelected = self.settings.mode === 'multi';
1134 self.initializePlugins(self.settings.plugins);
1135 self.setupCallbacks();
1136 self.setupTemplates();
1141 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1143 MicroEvent.mixin(Selectize);
1144 MicroPlugin.mixin(Selectize);
1147 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1149 $.extend(Selectize.prototype, {
1152 * Creates all elements and sets up event bindings.
1156 var settings = self.settings;
1157 var eventNS = self.eventNS;
1158 var $window = $(window);
1159 var $document = $(document);
1160 var $input = self.$input;
1166 var $dropdown_content;
1167 var $dropdown_parent;
1172 var classes_plugins;
1174 inputMode = self.settings.mode;
1175 classes = $input.attr('class') || '';
1177 $wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode);
1178 $control = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper);
1179 $control_input = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
1180 $dropdown_parent = $(settings.dropdownParent || $wrapper);
1181 $dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent);
1182 $dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
1184 if(self.settings.copyClassesToDropdown) {
1185 $dropdown.addClass(classes);
1189 width: $input[0].style.width
1192 if (self.plugins.names.length) {
1193 classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
1194 $wrapper.addClass(classes_plugins);
1195 $dropdown.addClass(classes_plugins);
1198 if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
1199 $input.attr('multiple', 'multiple');
1202 if (self.settings.placeholder) {
1203 $control_input.attr('placeholder', settings.placeholder);
1206 // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
1207 if (!self.settings.splitOn && self.settings.delimiter) {
1208 var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1209 self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
1212 if ($input.attr('autocorrect')) {
1213 $control_input.attr('autocorrect', $input.attr('autocorrect'));
1216 if ($input.attr('autocapitalize')) {
1217 $control_input.attr('autocapitalize', $input.attr('autocapitalize'));
1220 self.$wrapper = $wrapper;
1221 self.$control = $control;
1222 self.$control_input = $control_input;
1223 self.$dropdown = $dropdown;
1224 self.$dropdown_content = $dropdown_content;
1226 $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
1227 $dropdown.on('mousedown click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
1228 watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
1229 autoGrow($control_input);
1232 mousedown : function() { return self.onMouseDown.apply(self, arguments); },
1233 click : function() { return self.onClick.apply(self, arguments); }
1237 mousedown : function(e) { e.stopPropagation(); },
1238 keydown : function() { return self.onKeyDown.apply(self, arguments); },
1239 keyup : function() { return self.onKeyUp.apply(self, arguments); },
1240 keypress : function() { return self.onKeyPress.apply(self, arguments); },
1241 resize : function() { self.positionDropdown.apply(self, []); },
1242 blur : function() { return self.onBlur.apply(self, arguments); },
1243 focus : function() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); },
1244 paste : function() { return self.onPaste.apply(self, arguments); }
1247 $document.on('keydown' + eventNS, function(e) {
1248 self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
1249 self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
1250 self.isShiftDown = e.shiftKey;
1253 $document.on('keyup' + eventNS, function(e) {
1254 if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
1255 if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
1256 if (e.keyCode === KEY_CMD) self.isCmdDown = false;
1259 $document.on('mousedown' + eventNS, function(e) {
1260 if (self.isFocused) {
1261 // prevent events on the dropdown scrollbar from causing the control to blur
1262 if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) {
1265 // blur on click outside
1266 if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
1267 self.blur(e.target);
1272 $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
1274 self.positionDropdown.apply(self, arguments);
1277 $window.on('mousemove' + eventNS, function() {
1278 self.ignoreHover = false;
1281 // store original children and tab index so that they can be
1282 // restored when the destroy() method is called.
1283 this.revertSettings = {
1284 $children : $input.children().detach(),
1285 tabindex : $input.attr('tabindex')
1288 $input.attr('tabindex', -1).hide().after(self.$wrapper);
1290 if ($.isArray(settings.items)) {
1291 self.setValue(settings.items);
1292 delete settings.items;
1295 // feature detect for the validation API
1296 if (SUPPORTS_VALIDITY_API) {
1297 $input.on('invalid' + eventNS, function(e) {
1299 self.isInvalid = true;
1300 self.refreshState();
1304 self.updateOriginalInput();
1305 self.refreshItems();
1306 self.refreshState();
1307 self.updatePlaceholder();
1308 self.isSetup = true;
1310 if ($input.is(':disabled')) {
1314 self.on('change', this.onChange);
1316 $input.data('selectize', self);
1317 $input.addClass('selectized');
1318 self.trigger('initialize');
1321 if (settings.preload === true) {
1322 self.onSearchChange('');
1328 * Sets up default rendering functions.
1330 setupTemplates: function() {
1332 var field_label = self.settings.labelField;
1333 var field_optgroup = self.settings.optgroupLabelField;
1336 'optgroup': function(data) {
1337 return '<div class="optgroup">' + data.html + '</div>';
1339 'optgroup_header': function(data, escape) {
1340 return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
1342 'option': function(data, escape) {
1343 return '<div class="option">' + escape(data[field_label]) + '</div>';
1345 'item': function(data, escape) {
1346 return '<div class="item">' + escape(data[field_label]) + '</div>';
1348 'option_create': function(data, escape) {
1349 return '<div class="create">Add <strong>' + escape(data.input) + '</strong>…</div>';
1353 self.settings.render = $.extend({}, templates, self.settings.render);
1357 * Maps fired events to callbacks provided
1358 * in the settings used when creating the control.
1360 setupCallbacks: function() {
1361 var key, fn, callbacks = {
1362 'initialize' : 'onInitialize',
1363 'change' : 'onChange',
1364 'item_add' : 'onItemAdd',
1365 'item_remove' : 'onItemRemove',
1366 'clear' : 'onClear',
1367 'option_add' : 'onOptionAdd',
1368 'option_remove' : 'onOptionRemove',
1369 'option_clear' : 'onOptionClear',
1370 'optgroup_add' : 'onOptionGroupAdd',
1371 'optgroup_remove' : 'onOptionGroupRemove',
1372 'optgroup_clear' : 'onOptionGroupClear',
1373 'dropdown_open' : 'onDropdownOpen',
1374 'dropdown_close' : 'onDropdownClose',
1377 'focus' : 'onFocus',
1381 for (key in callbacks) {
1382 if (callbacks.hasOwnProperty(key)) {
1383 fn = this.settings[callbacks[key]];
1384 if (fn) this.on(key, fn);
1390 * Triggered when the main control element
1391 * has a click event.
1396 onClick: function(e) {
1399 // necessary for mobile webkit devices (manual focus triggering
1400 // is ignored unless invoked within a click event)
1401 if (!self.isFocused) {
1408 * Triggered when the main control element
1409 * has a mouse down event.
1414 onMouseDown: function(e) {
1416 var defaultPrevented = e.isDefaultPrevented();
1417 var $target = $(e.target);
1419 if (self.isFocused) {
1420 // retain focus by preventing native handling. if the
1421 // event target is the input it should not be modified.
1422 // otherwise, text selection within the input won't work.
1423 if (e.target !== self.$control_input[0]) {
1424 if (self.settings.mode === 'single') {
1426 self.isOpen ? self.close() : self.open();
1427 } else if (!defaultPrevented) {
1428 self.setActiveItem(null);
1433 // give control focus
1434 if (!defaultPrevented) {
1435 window.setTimeout(function() {
1443 * Triggered when the value of the control has been changed.
1444 * This should propagate the event to the original DOM
1445 * input / select element.
1447 onChange: function() {
1448 this.$input.trigger('change');
1452 * Triggered on <input> paste.
1455 * @returns {boolean}
1457 onPaste: function(e) {
1459 if (self.isFull() || self.isInputHidden || self.isLocked) {
1462 // If a regex or string is included, this will split the pasted
1463 // input and create Items for each separate value
1464 if (self.settings.splitOn) {
1465 setTimeout(function() {
1466 var splitInput = $.trim(self.$control_input.val() || '').split(self.settings.splitOn);
1467 for (var i = 0, n = splitInput.length; i < n; i++) {
1468 self.createItem(splitInput[i]);
1476 * Triggered on <input> keypress.
1479 * @returns {boolean}
1481 onKeyPress: function(e) {
1482 if (this.isLocked) return e && e.preventDefault();
1483 var character = String.fromCharCode(e.keyCode || e.which);
1484 if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
1492 * Triggered on <input> keydown.
1495 * @returns {boolean}
1497 onKeyDown: function(e) {
1498 var isInput = e.target === this.$control_input[0];
1501 if (self.isLocked) {
1502 if (e.keyCode !== KEY_TAB) {
1508 switch (e.keyCode) {
1510 if (self.isCmdDown) {
1518 e.stopPropagation();
1523 if (!e.ctrlKey || e.altKey) break;
1525 if (!self.isOpen && self.hasOptions) {
1527 } else if (self.$activeOption) {
1528 self.ignoreHover = true;
1529 var $next = self.getAdjacentOption(self.$activeOption, 1);
1530 if ($next.length) self.setActiveOption($next, true, true);
1535 if (!e.ctrlKey || e.altKey) break;
1537 if (self.$activeOption) {
1538 self.ignoreHover = true;
1539 var $prev = self.getAdjacentOption(self.$activeOption, -1);
1540 if ($prev.length) self.setActiveOption($prev, true, true);
1545 if (self.isOpen && self.$activeOption) {
1546 self.onOptionSelect({currentTarget: self.$activeOption});
1551 self.advanceSelection(-1, e);
1554 self.advanceSelection(1, e);
1557 if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
1558 self.onOptionSelect({currentTarget: self.$activeOption});
1560 // Default behaviour is to jump to the next field, we only want this
1561 // if the current field doesn't accept any more entries
1562 if (!self.isFull()) {
1566 if (self.settings.create && self.createItem()) {
1572 self.deleteSelection(e);
1576 if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
1583 * Triggered on <input> keyup.
1586 * @returns {boolean}
1588 onKeyUp: function(e) {
1591 if (self.isLocked) return e && e.preventDefault();
1592 var value = self.$control_input.val() || '';
1593 if (self.lastValue !== value) {
1594 self.lastValue = value;
1595 self.onSearchChange(value);
1596 self.refreshOptions();
1597 self.trigger('type', value);
1602 * Invokes the user-provide option provider / loader.
1604 * Note: this function is debounced in the Selectize
1605 * constructor (by `settings.loadDelay` milliseconds)
1607 * @param {string} value
1609 onSearchChange: function(value) {
1611 var fn = self.settings.load;
1613 if (self.loadedSearches.hasOwnProperty(value)) return;
1614 self.loadedSearches[value] = true;
1615 self.load(function(callback) {
1616 fn.apply(self, [value, callback]);
1621 * Triggered on <input> focus.
1623 * @param {object} e (optional)
1624 * @returns {boolean}
1626 onFocus: function(e) {
1628 var wasFocused = self.isFocused;
1630 if (self.isDisabled) {
1632 e && e.preventDefault();
1636 if (self.ignoreFocus) return;
1637 self.isFocused = true;
1638 if (self.settings.preload === 'focus') self.onSearchChange('');
1640 if (!wasFocused) self.trigger('focus');
1642 if (!self.$activeItems.length) {
1644 self.setActiveItem(null);
1645 self.refreshOptions(!!self.settings.openOnFocus);
1648 self.refreshState();
1652 * Triggered on <input> blur.
1655 * @param {Element} dest
1657 onBlur: function(e, dest) {
1659 if (!self.isFocused) return;
1660 self.isFocused = false;
1662 if (self.ignoreFocus) {
1664 } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) {
1665 // necessary to prevent IE closing the dropdown when the scrollbar is clicked
1666 self.ignoreBlur = true;
1671 var deactivate = function() {
1673 self.setTextboxValue('');
1674 self.setActiveItem(null);
1675 self.setActiveOption(null);
1676 self.setCaret(self.items.length);
1677 self.refreshState();
1679 // IE11 bug: element still marked as active
1680 (dest || document.body).focus();
1682 self.ignoreFocus = false;
1683 self.trigger('blur');
1686 self.ignoreFocus = true;
1687 if (self.settings.create && self.settings.createOnBlur) {
1688 self.createItem(null, false, deactivate);
1695 * Triggered when the user rolls over
1696 * an option in the autocomplete dropdown menu.
1699 * @returns {boolean}
1701 onOptionHover: function(e) {
1702 if (this.ignoreHover) return;
1703 this.setActiveOption(e.currentTarget, false);
1707 * Triggered when the user clicks on an option
1708 * in the autocomplete dropdown menu.
1711 * @returns {boolean}
1713 onOptionSelect: function(e) {
1714 var value, $target, $option, self = this;
1716 if (e.preventDefault) {
1718 e.stopPropagation();
1721 $target = $(e.currentTarget);
1722 if ($target.hasClass('create')) {
1723 self.createItem(null, function() {
1724 if (self.settings.closeAfterSelect) {
1729 value = $target.attr('data-value');
1730 if (typeof value !== 'undefined') {
1731 self.lastQuery = null;
1732 self.setTextboxValue('');
1733 self.addItem(value);
1734 if (self.settings.closeAfterSelect) {
1736 } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
1737 self.setActiveOption(self.getOption(value));
1744 * Triggered when the user clicks on an item
1745 * that has been selected.
1748 * @returns {boolean}
1750 onItemSelect: function(e) {
1753 if (self.isLocked) return;
1754 if (self.settings.mode === 'multi') {
1756 self.setActiveItem(e.currentTarget, e);
1761 * Invokes the provided method that provides
1762 * results to a callback---which are then added
1763 * as options to the control.
1765 * @param {function} fn
1767 load: function(fn) {
1769 var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
1772 fn.apply(self, [function(results) {
1773 self.loading = Math.max(self.loading - 1, 0);
1774 if (results && results.length) {
1775 self.addOption(results);
1776 self.refreshOptions(self.isFocused && !self.isInputHidden);
1778 if (!self.loading) {
1779 $wrapper.removeClass(self.settings.loadingClass);
1781 self.trigger('load', results);
1786 * Sets the input field of the control to the specified value.
1788 * @param {string} value
1790 setTextboxValue: function(value) {
1791 var $input = this.$control_input;
1792 var changed = $input.val() !== value;
1794 $input.val(value).triggerHandler('update');
1795 this.lastValue = value;
1800 * Returns the value of the control. If multiple items
1801 * can be selected (e.g. <select multiple>), this returns
1802 * an array. If only one item can be selected, this
1807 getValue: function() {
1808 if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
1811 return this.items.join(this.settings.delimiter);
1816 * Resets the selected items to the given value.
1818 * @param {mixed} value
1820 setValue: function(value, silent) {
1821 var events = silent ? [] : ['change'];
1823 debounce_events(this, events, function() {
1825 this.addItems(value, silent);
1830 * Sets the selected item.
1832 * @param {object} $item
1833 * @param {object} e (optional)
1835 setActiveItem: function($item, e) {
1838 var i, idx, begin, end, item, swap;
1841 if (self.settings.mode === 'single') return;
1844 // clear the active selection
1845 if (!$item.length) {
1846 $(self.$activeItems).removeClass('active');
1847 self.$activeItems = [];
1848 if (self.isFocused) {
1855 eventName = e && e.type.toLowerCase();
1857 if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
1858 $last = self.$control.children('.active:last');
1859 begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
1860 end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
1866 for (i = begin; i <= end; i++) {
1867 item = self.$control[0].childNodes[i];
1868 if (self.$activeItems.indexOf(item) === -1) {
1869 $(item).addClass('active');
1870 self.$activeItems.push(item);
1874 } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
1875 if ($item.hasClass('active')) {
1876 idx = self.$activeItems.indexOf($item[0]);
1877 self.$activeItems.splice(idx, 1);
1878 $item.removeClass('active');
1880 self.$activeItems.push($item.addClass('active')[0]);
1883 $(self.$activeItems).removeClass('active');
1884 self.$activeItems = [$item.addClass('active')[0]];
1887 // ensure control has focus
1889 if (!this.isFocused) {
1895 * Sets the selected item in the dropdown menu
1896 * of available options.
1898 * @param {object} $object
1899 * @param {boolean} scroll
1900 * @param {boolean} animate
1902 setActiveOption: function($option, scroll, animate) {
1903 var height_menu, height_item, y;
1904 var scroll_top, scroll_bottom;
1907 if (self.$activeOption) self.$activeOption.removeClass('active');
1908 self.$activeOption = null;
1910 $option = $($option);
1911 if (!$option.length) return;
1913 self.$activeOption = $option.addClass('active');
1915 if (scroll || !isset(scroll)) {
1917 height_menu = self.$dropdown_content.height();
1918 height_item = self.$activeOption.outerHeight(true);
1919 scroll = self.$dropdown_content.scrollTop() || 0;
1920 y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
1922 scroll_bottom = y - height_menu + height_item;
1924 if (y + height_item > height_menu + scroll) {
1925 self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
1926 } else if (y < scroll) {
1927 self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
1934 * Selects all items (CTRL + A).
1936 selectAll: function() {
1938 if (self.settings.mode === 'single') return;
1940 self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
1941 if (self.$activeItems.length) {
1949 * Hides the input element out of view, while
1950 * retaining its focus.
1952 hideInput: function() {
1955 self.setTextboxValue('');
1956 self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : -10000});
1957 self.isInputHidden = true;
1961 * Restores input visibility.
1963 showInput: function() {
1964 this.$control_input.css({opacity: 1, position: 'relative', left: 0});
1965 this.isInputHidden = false;
1969 * Gives the control focus.
1973 if (self.isDisabled) return;
1975 self.ignoreFocus = true;
1976 self.$control_input[0].focus();
1977 window.setTimeout(function() {
1978 self.ignoreFocus = false;
1984 * Forces the control out of focus.
1986 * @param {Element} dest
1988 blur: function(dest) {
1989 this.$control_input[0].blur();
1990 this.onBlur(null, dest);
1994 * Returns a function that scores an object
1995 * to show how good of a match it is to the
1998 * @param {string} query
1999 * @param {object} options
2000 * @return {function}
2002 getScoreFunction: function(query) {
2003 return this.sifter.getScoreFunction(query, this.getSearchOptions());
2007 * Returns search options for sifter (the system
2008 * for scoring and sorting results).
2010 * @see https://github.com/brianreavis/sifter.js
2013 getSearchOptions: function() {
2014 var settings = this.settings;
2015 var sort = settings.sortField;
2016 if (typeof sort === 'string') {
2017 sort = [{field: sort}];
2021 fields : settings.searchField,
2022 conjunction : settings.searchConjunction,
2028 * Searches through available options and returns
2029 * a sorted array of matches.
2031 * Returns an object containing:
2038 * @param {string} query
2041 search: function(query) {
2042 var i, value, score, result, calculateScore;
2044 var settings = self.settings;
2045 var options = this.getSearchOptions();
2047 // validate user-provided result scoring function
2048 if (settings.score) {
2049 calculateScore = self.settings.score.apply(this, [query]);
2050 if (typeof calculateScore !== 'function') {
2051 throw new Error('Selectize "score" setting must be a function that returns a function');
2056 if (query !== self.lastQuery) {
2057 self.lastQuery = query;
2058 result = self.sifter.search(query, $.extend(options, {score: calculateScore}));
2059 self.currentResults = result;
2061 result = $.extend(true, {}, self.currentResults);
2064 // filter out selected items
2065 if (settings.hideSelected) {
2066 for (i = result.items.length - 1; i >= 0; i--) {
2067 if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
2068 result.items.splice(i, 1);
2077 * Refreshes the list of available options shown
2078 * in the autocomplete dropdown menu.
2080 * @param {boolean} triggerDropdown
2082 refreshOptions: function(triggerDropdown) {
2083 var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
2084 var $active, $active_before, $create;
2086 if (typeof triggerDropdown === 'undefined') {
2087 triggerDropdown = true;
2091 var query = $.trim(self.$control_input.val());
2092 var results = self.search(query);
2093 var $dropdown_content = self.$dropdown_content;
2094 var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
2097 n = results.items.length;
2098 if (typeof self.settings.maxOptions === 'number') {
2099 n = Math.min(n, self.settings.maxOptions);
2102 // render and group available options individually
2106 for (i = 0; i < n; i++) {
2107 option = self.options[results.items[i].id];
2108 option_html = self.render('option', option);
2109 optgroup = option[self.settings.optgroupField] || '';
2110 optgroups = $.isArray(optgroup) ? optgroup : [optgroup];
2112 for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
2113 optgroup = optgroups[j];
2114 if (!self.optgroups.hasOwnProperty(optgroup)) {
2117 if (!groups.hasOwnProperty(optgroup)) {
2118 groups[optgroup] = [];
2119 groups_order.push(optgroup);
2121 groups[optgroup].push(option_html);
2126 if (this.settings.lockOptgroupOrder) {
2127 groups_order.sort(function(a, b) {
2128 var a_order = self.optgroups[a].$order || 0;
2129 var b_order = self.optgroups[b].$order || 0;
2130 return a_order - b_order;
2134 // render optgroup headers & join groups
2136 for (i = 0, n = groups_order.length; i < n; i++) {
2137 optgroup = groups_order[i];
2138 if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].length) {
2139 // render the optgroup header and options within it,
2140 // then pass it to the wrapper template
2141 html_children = self.render('optgroup_header', self.optgroups[optgroup]) || '';
2142 html_children += groups[optgroup].join('');
2143 html.push(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
2147 html.push(groups[optgroup].join(''));
2151 $dropdown_content.html(html.join(''));
2153 // highlight matching terms inline
2154 if (self.settings.highlight && results.query.length && results.tokens.length) {
2155 for (i = 0, n = results.tokens.length; i < n; i++) {
2156 highlight($dropdown_content, results.tokens[i].regex);
2160 // add "selected" class to selected options
2161 if (!self.settings.hideSelected) {
2162 for (i = 0, n = self.items.length; i < n; i++) {
2163 self.getOption(self.items[i]).addClass('selected');
2167 // add create option
2168 has_create_option = self.canCreate(query);
2169 if (has_create_option) {
2170 $dropdown_content.prepend(self.render('option_create', {input: query}));
2171 $create = $($dropdown_content[0].childNodes[0]);
2175 self.hasOptions = results.items.length > 0 || has_create_option;
2176 if (self.hasOptions) {
2177 if (results.items.length > 0) {
2178 $active_before = active_before && self.getOption(active_before);
2179 if ($active_before && $active_before.length) {
2180 $active = $active_before;
2181 } else if (self.settings.mode === 'single' && self.items.length) {
2182 $active = self.getOption(self.items[0]);
2184 if (!$active || !$active.length) {
2185 if ($create && !self.settings.addPrecedence) {
2186 $active = self.getAdjacentOption($create, 1);
2188 $active = $dropdown_content.find('[data-selectable]:first');
2194 self.setActiveOption($active);
2195 if (triggerDropdown && !self.isOpen) { self.open(); }
2197 self.setActiveOption(null);
2198 if (triggerDropdown && self.isOpen) { self.close(); }
2203 * Adds an available option. If it already exists,
2204 * nothing will happen. Note: this does not refresh
2205 * the options list dropdown (use `refreshOptions`
2210 * this.addOption(data)
2212 * @param {object|array} data
2214 addOption: function(data) {
2215 var i, n, value, self = this;
2217 if ($.isArray(data)) {
2218 for (i = 0, n = data.length; i < n; i++) {
2219 self.addOption(data[i]);
2224 if (value = self.registerOption(data)) {
2225 self.userOptions[value] = true;
2226 self.lastQuery = null;
2227 self.trigger('option_add', value, data);
2232 * Registers an option to the pool of options.
2234 * @param {object} data
2235 * @return {boolean|string}
2237 registerOption: function(data) {
2238 var key = hash_key(data[this.settings.valueField]);
2239 if (!key || this.options.hasOwnProperty(key)) return false;
2240 data.$order = data.$order || ++this.order;
2241 this.options[key] = data;
2246 * Registers an option group to the pool of option groups.
2248 * @param {object} data
2249 * @return {boolean|string}
2251 registerOptionGroup: function(data) {
2252 var key = hash_key(data[this.settings.optgroupValueField]);
2253 if (!key) return false;
2255 data.$order = data.$order || ++this.order;
2256 this.optgroups[key] = data;
2261 * Registers a new optgroup for options
2262 * to be bucketed into.
2264 * @param {string} id
2265 * @param {object} data
2267 addOptionGroup: function(id, data) {
2268 data[this.settings.optgroupValueField] = id;
2269 if (id = this.registerOptionGroup(data)) {
2270 this.trigger('optgroup_add', id, data);
2275 * Removes an existing option group.
2277 * @param {string} id
2279 removeOptionGroup: function(id) {
2280 if (this.optgroups.hasOwnProperty(id)) {
2281 delete this.optgroups[id];
2282 this.renderCache = {};
2283 this.trigger('optgroup_remove', id);
2288 * Clears all existing option groups.
2290 clearOptionGroups: function() {
2291 this.optgroups = {};
2292 this.renderCache = {};
2293 this.trigger('optgroup_clear');
2297 * Updates an option available for selection. If
2298 * it is visible in the selected items or options
2299 * dropdown, it will be re-rendered automatically.
2301 * @param {string} value
2302 * @param {object} data
2304 updateOption: function(value, data) {
2306 var $item, $item_new;
2307 var value_new, index_item, cache_items, cache_options, order_old;
2309 value = hash_key(value);
2310 value_new = hash_key(data[self.settings.valueField]);
2313 if (value === null) return;
2314 if (!self.options.hasOwnProperty(value)) return;
2315 if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
2317 order_old = self.options[value].$order;
2319 // update references
2320 if (value_new !== value) {
2321 delete self.options[value];
2322 index_item = self.items.indexOf(value);
2323 if (index_item !== -1) {
2324 self.items.splice(index_item, 1, value_new);
2327 data.$order = data.$order || order_old;
2328 self.options[value_new] = data;
2330 // invalidate render cache
2331 cache_items = self.renderCache['item'];
2332 cache_options = self.renderCache['option'];
2335 delete cache_items[value];
2336 delete cache_items[value_new];
2338 if (cache_options) {
2339 delete cache_options[value];
2340 delete cache_options[value_new];
2343 // update the item if it's selected
2344 if (self.items.indexOf(value_new) !== -1) {
2345 $item = self.getItem(value);
2346 $item_new = $(self.render('item', data));
2347 if ($item.hasClass('active')) $item_new.addClass('active');
2348 $item.replaceWith($item_new);
2351 // invalidate last query because we might have updated the sortField
2352 self.lastQuery = null;
2354 // update dropdown contents
2356 self.refreshOptions(false);
2361 * Removes a single option.
2363 * @param {string} value
2364 * @param {boolean} silent
2366 removeOption: function(value, silent) {
2368 value = hash_key(value);
2370 var cache_items = self.renderCache['item'];
2371 var cache_options = self.renderCache['option'];
2372 if (cache_items) delete cache_items[value];
2373 if (cache_options) delete cache_options[value];
2375 delete self.userOptions[value];
2376 delete self.options[value];
2377 self.lastQuery = null;
2378 self.trigger('option_remove', value);
2379 self.removeItem(value, silent);
2383 * Clears all options.
2385 clearOptions: function() {
2388 self.loadedSearches = {};
2389 self.userOptions = {};
2390 self.renderCache = {};
2391 self.options = self.sifter.items = {};
2392 self.lastQuery = null;
2393 self.trigger('option_clear');
2398 * Returns the jQuery element of the option
2399 * matching the given value.
2401 * @param {string} value
2404 getOption: function(value) {
2405 return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
2409 * Returns the jQuery element of the next or
2410 * previous selectable option.
2412 * @param {object} $option
2413 * @param {int} direction can be 1 for next or -1 for previous
2416 getAdjacentOption: function($option, direction) {
2417 var $options = this.$dropdown.find('[data-selectable]');
2418 var index = $options.index($option) + direction;
2420 return index >= 0 && index < $options.length ? $options.eq(index) : $();
2424 * Finds the first element with a "data-value" attribute
2425 * that matches the given value.
2427 * @param {mixed} value
2428 * @param {object} $els
2431 getElementWithValue: function(value, $els) {
2432 value = hash_key(value);
2434 if (typeof value !== 'undefined' && value !== null) {
2435 for (var i = 0, n = $els.length; i < n; i++) {
2436 if ($els[i].getAttribute('data-value') === value) {
2446 * Returns the jQuery element of the item
2447 * matching the given value.
2449 * @param {string} value
2452 getItem: function(value) {
2453 return this.getElementWithValue(value, this.$control.children());
2457 * "Selects" multiple items at once. Adds them to the list
2458 * at the current caret position.
2460 * @param {string} value
2461 * @param {boolean} silent
2463 addItems: function(values, silent) {
2464 var items = $.isArray(values) ? values : [values];
2465 for (var i = 0, n = items.length; i < n; i++) {
2466 this.isPending = (i < n - 1);
2467 this.addItem(items[i], silent);
2472 * "Selects" an item. Adds it to the list
2473 * at the current caret position.
2475 * @param {string} value
2476 * @param {boolean} silent
2478 addItem: function(value, silent) {
2479 var events = silent ? [] : ['change'];
2481 debounce_events(this, events, function() {
2482 var $item, $option, $options;
2484 var inputMode = self.settings.mode;
2485 var i, active, value_next, wasFull;
2486 value = hash_key(value);
2488 if (self.items.indexOf(value) !== -1) {
2489 if (inputMode === 'single') self.close();
2493 if (!self.options.hasOwnProperty(value)) return;
2494 if (inputMode === 'single') self.clear();
2495 if (inputMode === 'multi' && self.isFull()) return;
2497 $item = $(self.render('item', self.options[value]));
2498 wasFull = self.isFull();
2499 self.items.splice(self.caretPos, 0, value);
2500 self.insertAtCaret($item);
2501 if (!self.isPending || (!wasFull && self.isFull())) {
2502 self.refreshState();
2506 $options = self.$dropdown_content.find('[data-selectable]');
2508 // update menu / remove the option (if this is not one item being added as part of series)
2509 if (!self.isPending) {
2510 $option = self.getOption(value);
2511 value_next = self.getAdjacentOption($option, 1).attr('data-value');
2512 self.refreshOptions(self.isFocused && inputMode !== 'single');
2514 self.setActiveOption(self.getOption(value_next));
2518 // hide the menu if the maximum number of items have been selected or no options are left
2519 if (!$options.length || self.isFull()) {
2522 self.positionDropdown();
2525 self.updatePlaceholder();
2526 self.trigger('item_add', value, $item);
2527 self.updateOriginalInput({silent: silent});
2533 * Removes the selected item matching
2534 * the provided value.
2536 * @param {string} value
2538 removeItem: function(value, silent) {
2542 $item = (typeof value === 'object') ? value : self.getItem(value);
2543 value = hash_key($item.attr('data-value'));
2544 i = self.items.indexOf(value);
2548 if ($item.hasClass('active')) {
2549 idx = self.$activeItems.indexOf($item[0]);
2550 self.$activeItems.splice(idx, 1);
2553 self.items.splice(i, 1);
2554 self.lastQuery = null;
2555 if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
2556 self.removeOption(value, silent);
2559 if (i < self.caretPos) {
2560 self.setCaret(self.caretPos - 1);
2563 self.refreshState();
2564 self.updatePlaceholder();
2565 self.updateOriginalInput({silent: silent});
2566 self.positionDropdown();
2567 self.trigger('item_remove', value, $item);
2572 * Invokes the `create` method provided in the
2573 * selectize options that should provide the data
2574 * for the new item, given the user input.
2576 * Once this completes, it will be added
2579 * @param {string} value
2580 * @param {boolean} [triggerDropdown]
2581 * @param {function} [callback]
2584 createItem: function(input, triggerDropdown) {
2586 var caret = self.caretPos;
2587 input = input || $.trim(self.$control_input.val() || '');
2589 var callback = arguments[arguments.length - 1];
2590 if (typeof callback !== 'function') callback = function() {};
2592 if (typeof triggerDropdown !== 'boolean') {
2593 triggerDropdown = true;
2596 if (!self.canCreate(input)) {
2603 var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
2605 data[self.settings.labelField] = input;
2606 data[self.settings.valueField] = input;
2610 var create = once(function(data) {
2613 if (!data || typeof data !== 'object') return callback();
2614 var value = hash_key(data[self.settings.valueField]);
2615 if (typeof value !== 'string') return callback();
2617 self.setTextboxValue('');
2618 self.addOption(data);
2619 self.setCaret(caret);
2620 self.addItem(value);
2621 self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
2625 var output = setup.apply(this, [input, create]);
2626 if (typeof output !== 'undefined') {
2634 * Re-renders the selected item lists.
2636 refreshItems: function() {
2637 this.lastQuery = null;
2640 this.addItem(this.items);
2643 this.refreshState();
2644 this.updateOriginalInput();
2648 * Updates all state-dependent attributes
2651 refreshState: function() {
2652 var invalid, self = this;
2653 if (self.isRequired) {
2654 if (self.items.length) self.isInvalid = false;
2655 self.$control_input.prop('required', invalid);
2657 self.refreshClasses();
2661 * Updates all state-dependent CSS classes.
2663 refreshClasses: function() {
2665 var isFull = self.isFull();
2666 var isLocked = self.isLocked;
2669 .toggleClass('rtl', self.rtl);
2672 .toggleClass('focus', self.isFocused)
2673 .toggleClass('disabled', self.isDisabled)
2674 .toggleClass('required', self.isRequired)
2675 .toggleClass('invalid', self.isInvalid)
2676 .toggleClass('locked', isLocked)
2677 .toggleClass('full', isFull).toggleClass('not-full', !isFull)
2678 .toggleClass('input-active', self.isFocused && !self.isInputHidden)
2679 .toggleClass('dropdown-active', self.isOpen)
2680 .toggleClass('has-options', !$.isEmptyObject(self.options))
2681 .toggleClass('has-items', self.items.length > 0);
2683 self.$control_input.data('grow', !isFull && !isLocked);
2687 * Determines whether or not more items can be added
2688 * to the control without exceeding the user-defined maximum.
2690 * @returns {boolean}
2692 isFull: function() {
2693 return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
2697 * Refreshes the original <select> or <input>
2698 * element to reflect the current state.
2700 updateOriginalInput: function(opts) {
2701 var i, n, options, label, self = this;
2704 if (self.tagType === TAG_SELECT) {
2706 for (i = 0, n = self.items.length; i < n; i++) {
2707 label = self.options[self.items[i]][self.settings.labelField] || '';
2708 options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>');
2710 if (!options.length && !this.$input.attr('multiple')) {
2711 options.push('<option value="" selected="selected"></option>');
2713 self.$input.html(options.join(''));
2715 self.$input.val(self.getValue());
2716 self.$input.attr('value',self.$input.val());
2721 self.trigger('change', self.$input.val());
2727 * Shows/hide the input placeholder depending
2728 * on if there items in the list already.
2730 updatePlaceholder: function() {
2731 if (!this.settings.placeholder) return;
2732 var $input = this.$control_input;
2734 if (this.items.length) {
2735 $input.removeAttr('placeholder');
2737 $input.attr('placeholder', this.settings.placeholder);
2739 $input.triggerHandler('update', {force: true});
2743 * Shows the autocomplete dropdown containing
2744 * the available options.
2749 if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
2752 self.refreshState();
2753 self.$dropdown.css({visibility: 'hidden', display: 'block'});
2754 self.positionDropdown();
2755 self.$dropdown.css({visibility: 'visible'});
2756 self.trigger('dropdown_open', self.$dropdown);
2760 * Closes the autocomplete dropdown menu.
2764 var trigger = self.isOpen;
2766 if (self.settings.mode === 'single' && self.items.length) {
2770 self.isOpen = false;
2771 self.$dropdown.hide();
2772 self.setActiveOption(null);
2773 self.refreshState();
2775 if (trigger) self.trigger('dropdown_close', self.$dropdown);
2779 * Calculates and applies the appropriate
2780 * position of the dropdown.
2782 positionDropdown: function() {
2783 var $control = this.$control;
2784 var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
2785 offset.top += $control.outerHeight(true);
2787 this.$dropdown.css({
2788 width : $control.outerWidth(),
2795 * Resets / clears all selected items
2798 * @param {boolean} silent
2800 clear: function(silent) {
2803 if (!self.items.length) return;
2804 self.$control.children(':not(input)').remove();
2806 self.lastQuery = null;
2808 self.setActiveItem(null);
2809 self.updatePlaceholder();
2810 self.updateOriginalInput({silent: silent});
2811 self.refreshState();
2813 self.trigger('clear');
2817 * A helper method for inserting an element
2818 * at the current caret position.
2820 * @param {object} $el
2822 insertAtCaret: function($el) {
2823 var caret = Math.min(this.caretPos, this.items.length);
2825 this.$control.prepend($el);
2827 $(this.$control[0].childNodes[caret]).before($el);
2829 this.setCaret(caret + 1);
2833 * Removes the current selected item(s).
2835 * @param {object} e (optional)
2836 * @returns {boolean}
2838 deleteSelection: function(e) {
2839 var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
2842 direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
2843 selection = getSelection(self.$control_input[0]);
2845 if (self.$activeOption && !self.settings.hideSelected) {
2846 option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
2849 // determine items that will be removed
2852 if (self.$activeItems.length) {
2853 $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
2854 caret = self.$control.children(':not(input)').index($tail);
2855 if (direction > 0) { caret++; }
2857 for (i = 0, n = self.$activeItems.length; i < n; i++) {
2858 values.push($(self.$activeItems[i]).attr('data-value'));
2862 e.stopPropagation();
2864 } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
2865 if (direction < 0 && selection.start === 0 && selection.length === 0) {
2866 values.push(self.items[self.caretPos - 1]);
2867 } else if (direction > 0 && selection.start === self.$control_input.val().length) {
2868 values.push(self.items[self.caretPos]);
2872 // allow the callback to abort
2873 if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
2878 if (typeof caret !== 'undefined') {
2879 self.setCaret(caret);
2881 while (values.length) {
2882 self.removeItem(values.pop());
2886 self.positionDropdown();
2887 self.refreshOptions(true);
2889 // select previous option
2890 if (option_select) {
2891 $option_select = self.getOption(option_select);
2892 if ($option_select.length) {
2893 self.setActiveOption($option_select);
2901 * Selects the previous / next item (depending
2902 * on the `direction` argument).
2907 * @param {int} direction
2908 * @param {object} e (optional)
2910 advanceSelection: function(direction, e) {
2911 var tail, selection, idx, valueLength, cursorAtEdge, $tail;
2914 if (direction === 0) return;
2915 if (self.rtl) direction *= -1;
2917 tail = direction > 0 ? 'last' : 'first';
2918 selection = getSelection(self.$control_input[0]);
2920 if (self.isFocused && !self.isInputHidden) {
2921 valueLength = self.$control_input.val().length;
2922 cursorAtEdge = direction < 0
2923 ? selection.start === 0 && selection.length === 0
2924 : selection.start === valueLength;
2926 if (cursorAtEdge && !valueLength) {
2927 self.advanceCaret(direction, e);
2930 $tail = self.$control.children('.active:' + tail);
2932 idx = self.$control.children(':not(input)').index($tail);
2933 self.setActiveItem(null);
2934 self.setCaret(direction > 0 ? idx + 1 : idx);
2940 * Moves the caret left / right.
2942 * @param {int} direction
2943 * @param {object} e (optional)
2945 advanceCaret: function(direction, e) {
2946 var self = this, fn, $adj;
2948 if (direction === 0) return;
2950 fn = direction > 0 ? 'next' : 'prev';
2951 if (self.isShiftDown) {
2952 $adj = self.$control_input[fn]();
2955 self.setActiveItem($adj);
2956 e && e.preventDefault();
2959 self.setCaret(self.caretPos + direction);
2964 * Moves the caret to the specified index.
2968 setCaret: function(i) {
2971 if (self.settings.mode === 'single') {
2972 i = self.items.length;
2974 i = Math.max(0, Math.min(self.items.length, i));
2977 if(!self.isPending) {
2978 // the input must be moved by leaving it in place and moving the
2979 // siblings, due to the fact that focus cannot be restored once lost
2980 // on mobile webkit devices
2981 var j, n, fn, $children, $child;
2982 $children = self.$control.children(':not(input)');
2983 for (j = 0, n = $children.length; j < n; j++) {
2984 $child = $($children[j]).detach();
2986 self.$control_input.before($child);
2988 self.$control.append($child);
2997 * Disables user input on the control. Used while
2998 * items are being asynchronously created.
3002 this.isLocked = true;
3003 this.refreshState();
3007 * Re-enables user input on the control.
3009 unlock: function() {
3010 this.isLocked = false;
3011 this.refreshState();
3015 * Disables user input on the control completely.
3016 * While disabled, it cannot receive focus.
3018 disable: function() {
3020 self.$input.prop('disabled', true);
3021 self.$control_input.prop('disabled', true).prop('tabindex', -1);
3022 self.isDisabled = true;
3027 * Enables the control so that it can respond
3028 * to focus and user input.
3030 enable: function() {
3032 self.$input.prop('disabled', false);
3033 self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
3034 self.isDisabled = false;
3039 * Completely destroys the control and
3040 * unbinds all event listeners so that it can
3041 * be garbage collected.
3043 destroy: function() {
3045 var eventNS = self.eventNS;
3046 var revertSettings = self.revertSettings;
3048 self.trigger('destroy');
3050 self.$wrapper.remove();
3051 self.$dropdown.remove();
3055 .append(revertSettings.$children)
3056 .removeAttr('tabindex')
3057 .removeClass('selectized')
3058 .attr({tabindex: revertSettings.tabindex})
3061 self.$control_input.removeData('grow');
3062 self.$input.removeData('selectize');
3064 $(window).off(eventNS);
3065 $(document).off(eventNS);
3066 $(document.body).off(eventNS);
3068 delete self.$input[0].selectize;
3072 * A helper method for rendering "item" and
3073 * "option" templates, given the data.
3075 * @param {string} templateName
3076 * @param {object} data
3079 render: function(templateName, data) {
3080 var value, id, label;
3084 var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
3086 if (templateName === 'option' || templateName === 'item') {
3087 value = hash_key(data[self.settings.valueField]);
3091 // pull markup from cache if it exists
3093 if (!isset(self.renderCache[templateName])) {
3094 self.renderCache[templateName] = {};
3096 if (self.renderCache[templateName].hasOwnProperty(value)) {
3097 return self.renderCache[templateName][value];
3102 html = self.settings.render[templateName].apply(this, [data, escape_html]);
3104 // add mandatory attributes
3105 if (templateName === 'option' || templateName === 'option_create') {
3106 html = html.replace(regex_tag, '<$1 data-selectable');
3108 if (templateName === 'optgroup') {
3109 id = data[self.settings.optgroupValueField] || '';
3110 html = html.replace(regex_tag, '<$1 data-group="' + escape_replace(escape_html(id)) + '"');
3112 if (templateName === 'option' || templateName === 'item') {
3113 html = html.replace(regex_tag, '<$1 data-value="' + escape_replace(escape_html(value || '')) + '"');
3118 self.renderCache[templateName][value] = html;
3125 * Clears the render cache for a template. If
3126 * no template is given, clears all render
3129 * @param {string} templateName
3131 clearCache: function(templateName) {
3133 if (typeof templateName === 'undefined') {
3134 self.renderCache = {};
3136 delete self.renderCache[templateName];
3141 * Determines whether or not to display the
3142 * create item prompt, given a user input.
3144 * @param {string} input
3147 canCreate: function(input) {
3149 if (!self.settings.create) return false;
3150 var filter = self.settings.createFilter;
3152 && (typeof filter !== 'function' || filter.apply(self, [input]))
3153 && (typeof filter !== 'string' || new RegExp(filter).test(input))
3154 && (!(filter instanceof RegExp) || filter.test(input));
3160 Selectize.count = 0;
3161 Selectize.defaults = {
3167 splitOn: null, // regexp or string for splitting up values from a paste command
3171 createOnBlur: false,
3178 addPrecedence: false,
3181 allowEmptyOption: false,
3182 closeAfterSelect: false,
3186 loadingClass: 'loading',
3188 dataAttr: 'data-data',
3189 optgroupField: 'optgroup',
3190 valueField: 'value',
3192 optgroupLabelField: 'label',
3193 optgroupValueField: 'value',
3194 lockOptgroupOrder: false,
3196 sortField: '$order',
3197 searchField: ['text'],
3198 searchConjunction: 'and',
3201 wrapperClass: 'selectize-control',
3202 inputClass: 'selectize-input',
3203 dropdownClass: 'selectize-dropdown',
3204 dropdownContentClass: 'selectize-dropdown-content',
3206 dropdownParent: null,
3208 copyClassesToDropdown: true,
3211 load : null, // function(query, callback) { ... }
3212 score : null, // function(search) { ... }
3213 onInitialize : null, // function() { ... }
3214 onChange : null, // function(value) { ... }
3215 onItemAdd : null, // function(value, $item) { ... }
3216 onItemRemove : null, // function(value) { ... }
3217 onClear : null, // function() { ... }
3218 onOptionAdd : null, // function(value, data) { ... }
3219 onOptionRemove : null, // function(value) { ... }
3220 onOptionClear : null, // function() { ... }
3221 onOptionGroupAdd : null, // function(id, data) { ... }
3222 onOptionGroupRemove : null, // function(id) { ... }
3223 onOptionGroupClear : null, // function() { ... }
3224 onDropdownOpen : null, // function($dropdown) { ... }
3225 onDropdownClose : null, // function($dropdown) { ... }
3226 onType : null, // function(str) { ... }
3227 onDelete : null, // function(values) { ... }
3234 optgroup_header: null,
3242 $.fn.selectize = function(settings_user) {
3243 var defaults = $.fn.selectize.defaults;
3244 var settings = $.extend({}, defaults, settings_user);
3245 var attr_data = settings.dataAttr;
3246 var field_label = settings.labelField;
3247 var field_value = settings.valueField;
3248 var field_optgroup = settings.optgroupField;
3249 var field_optgroup_label = settings.optgroupLabelField;
3250 var field_optgroup_value = settings.optgroupValueField;
3252 var optionsMap = {};
3255 * Initializes selectize from a <input type="text"> element.
3257 * @param {object} $input
3258 * @param {object} settings_element
3260 var init_textbox = function($input, settings_element) {
3261 var i, n, values, option;
3263 var data_raw = $input.attr(attr_data);
3266 var value = $.trim($input.val() || '');
3267 if (!settings.allowEmptyOption && !value.length) return;
3268 values = value.split(settings.delimiter);
3269 for (i = 0, n = values.length; i < n; i++) {
3271 option[field_label] = values[i];
3272 option[field_value] = values[i];
3273 settings_element.options.push(option);
3275 settings_element.items = values;
3277 settings_element.options = JSON.parse(data_raw);
3278 for (i = 0, n = settings_element.options.length; i < n; i++) {
3279 settings_element.items.push(settings_element.options[i][field_value]);
3285 * Initializes selectize from a <select> element.
3287 * @param {object} $input
3288 * @param {object} settings_element
3290 var init_select = function($input, settings_element) {
3291 var i, n, tagName, $children, order = 0;
3292 var options = settings_element.options;
3294 var readData = function($el) {
3295 var data = attr_data && $el.attr(attr_data);
3296 if (typeof data === 'string' && data.length) {
3297 return JSON.parse(data);
3302 var addOption = function($option, group) {
3303 $option = $($option);
3305 var value = hash_key($option.attr('value'));
3306 if (!value && !settings.allowEmptyOption) return;
3308 // if the option already exists, it's probably been
3309 // duplicated in another optgroup. in this case, push
3310 // the current group to the "optgroup" property on the
3311 // existing option so that it's rendered in both places.
3312 if (optionsMap.hasOwnProperty(value)) {
3314 var arr = optionsMap[value][field_optgroup];
3316 optionsMap[value][field_optgroup] = group;
3317 } else if (!$.isArray(arr)) {
3318 optionsMap[value][field_optgroup] = [arr, group];
3326 var option = readData($option) || {};
3327 option[field_label] = option[field_label] || $option.text();
3328 option[field_value] = option[field_value] || value;
3329 option[field_optgroup] = option[field_optgroup] || group;
3331 optionsMap[value] = option;
3332 options.push(option);
3334 if ($option.is(':selected')) {
3335 settings_element.items.push(value);
3339 var addGroup = function($optgroup) {
3340 var i, n, id, optgroup, $options;
3342 $optgroup = $($optgroup);
3343 id = $optgroup.attr('label');
3346 optgroup = readData($optgroup) || {};
3347 optgroup[field_optgroup_label] = id;
3348 optgroup[field_optgroup_value] = id;
3349 settings_element.optgroups.push(optgroup);
3352 $options = $('option', $optgroup);
3353 for (i = 0, n = $options.length; i < n; i++) {
3354 addOption($options[i], id);
3358 settings_element.maxItems = $input.attr('multiple') ? null : 1;
3360 $children = $input.children();
3361 for (i = 0, n = $children.length; i < n; i++) {
3362 tagName = $children[i].tagName.toLowerCase();
3363 if (tagName === 'optgroup') {
3364 addGroup($children[i]);
3365 } else if (tagName === 'option') {
3366 addOption($children[i]);
3371 return this.each(function() {
3372 if (this.selectize) return;
3375 var $input = $(this);
3376 var tag_name = this.tagName.toLowerCase();
3377 var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
3378 if (!placeholder && !settings.allowEmptyOption) {
3379 placeholder = $input.children('option[value=""]').text();
3382 var settings_element = {
3383 'placeholder' : placeholder,
3389 if (tag_name === 'select') {
3390 init_select($input, settings_element);
3392 init_textbox($input, settings_element);
3395 instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
3399 $.fn.selectize.defaults = Selectize.defaults;
3400 $.fn.selectize.support = {
3401 validity: SUPPORTS_VALIDITY_API
3405 Selectize.define('drag_drop', function(options) {
3406 if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
3407 if (this.settings.mode !== 'multi') return;
3410 self.lock = (function() {
3411 var original = self.lock;
3413 var sortable = self.$control.data('sortable');
3414 if (sortable) sortable.disable();
3415 return original.apply(self, arguments);
3419 self.unlock = (function() {
3420 var original = self.unlock;
3422 var sortable = self.$control.data('sortable');
3423 if (sortable) sortable.enable();
3424 return original.apply(self, arguments);
3428 self.setup = (function() {
3429 var original = self.setup;
3431 original.apply(this, arguments);
3433 var $control = self.$control.sortable({
3434 items: '[data-value]',
3435 forcePlaceholderSize: true,
3436 disabled: self.isLocked,
3437 start: function(e, ui) {
3438 ui.placeholder.css('width', ui.helper.css('width'));
3439 $control.css({overflow: 'visible'});
3442 $control.css({overflow: 'hidden'});
3443 var active = self.$activeItems ? self.$activeItems.slice() : null;
3445 $control.children('[data-value]').each(function() {
3446 values.push($(this).attr('data-value'));
3448 self.setValue(values);
3449 self.setActiveItem(active);
3457 Selectize.define('dropdown_header', function(options) {
3460 options = $.extend({
3462 headerClass : 'selectize-dropdown-header',
3463 titleRowClass : 'selectize-dropdown-header-title',
3464 labelClass : 'selectize-dropdown-header-label',
3465 closeClass : 'selectize-dropdown-header-close',
3467 html: function(data) {
3469 '<div class="' + data.headerClass + '">' +
3470 '<div class="' + data.titleRowClass + '">' +
3471 '<span class="' + data.labelClass + '">' + data.title + '</span>' +
3472 '<a href="javascript:void(0)" class="' + data.closeClass + '">×</a>' +
3479 self.setup = (function() {
3480 var original = self.setup;
3482 original.apply(self, arguments);
3483 self.$dropdown_header = $(options.html(options));
3484 self.$dropdown.prepend(self.$dropdown_header);
3490 Selectize.define('optgroup_columns', function(options) {
3493 options = $.extend({
3494 equalizeWidth : true,
3495 equalizeHeight : true
3498 this.getAdjacentOption = function($option, direction) {
3499 var $options = $option.closest('[data-group]').find('[data-selectable]');
3500 var index = $options.index($option) + direction;
3502 return index >= 0 && index < $options.length ? $options.eq(index) : $();
3505 this.onKeyDown = (function() {
3506 var original = self.onKeyDown;
3507 return function(e) {
3508 var index, $option, $options, $optgroup;
3510 if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
3511 self.ignoreHover = true;
3512 $optgroup = this.$activeOption.closest('[data-group]');
3513 index = $optgroup.find('[data-selectable]').index(this.$activeOption);
3515 if(e.keyCode === KEY_LEFT) {
3516 $optgroup = $optgroup.prev('[data-group]');
3518 $optgroup = $optgroup.next('[data-group]');
3521 $options = $optgroup.find('[data-selectable]');
3522 $option = $options.eq(Math.min($options.length - 1, index));
3523 if ($option.length) {
3524 this.setActiveOption($option);
3529 return original.apply(this, arguments);
3533 var getScrollbarWidth = function() {
3535 var width = getScrollbarWidth.width;
3538 if (typeof width === 'undefined') {
3539 div = doc.createElement('div');
3540 div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
3541 div = div.firstChild;
3542 doc.body.appendChild(div);
3543 width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
3544 doc.body.removeChild(div);
3549 var equalizeSizes = function() {
3550 var i, n, height_max, width, width_last, width_parent, $optgroups;
3552 $optgroups = $('[data-group]', self.$dropdown_content);
3553 n = $optgroups.length;
3554 if (!n || !self.$dropdown_content.width()) return;
3556 if (options.equalizeHeight) {
3558 for (i = 0; i < n; i++) {
3559 height_max = Math.max(height_max, $optgroups.eq(i).height());
3561 $optgroups.css({height: height_max});
3564 if (options.equalizeWidth) {
3565 width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
3566 width = Math.round(width_parent / n);
3567 $optgroups.css({width: width});
3569 width_last = width_parent - width * (n - 1);
3570 $optgroups.eq(n - 1).css({width: width_last});
3575 if (options.equalizeHeight || options.equalizeWidth) {
3576 hook.after(this, 'positionDropdown', equalizeSizes);
3577 hook.after(this, 'refreshOptions', equalizeSizes);
3583 Selectize.define('remove_button', function(options) {
3584 if (this.settings.mode === 'single') return;
3586 options = $.extend({
3589 className : 'remove',
3594 var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
3597 * Appends an element as a child (with raw HTML).
3599 * @param {string} html_container
3600 * @param {string} html_element
3603 var append = function(html_container, html_element) {
3604 var pos = html_container.search(/(<\/[^>]+>\s*)$/);
3605 return html_container.substring(0, pos) + html_element + html_container.substring(pos);
3608 this.setup = (function() {
3609 var original = self.setup;
3611 // override the item rendering method to add the button to each
3612 if (options.append) {
3613 var render_item = self.settings.render.item;
3614 self.settings.render.item = function(data) {
3615 return append(render_item.apply(this, arguments), html);
3619 original.apply(this, arguments);
3621 // add event listener
3622 this.$control.on('click', '.' + options.className, function(e) {
3624 if (self.isLocked) return;
3626 var $item = $(e.currentTarget).parent();
3627 self.setActiveItem($item);
3628 if (self.deleteSelection()) {
3629 self.setCaret(self.items.length);
3638 Selectize.define('restore_on_backspace', function(options) {
3641 options.text = options.text || function(option) {
3642 return option[this.settings.labelField];
3645 this.onKeyDown = (function() {
3646 var original = self.onKeyDown;
3647 return function(e) {
3649 if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
3650 index = this.caretPos - 1;
3651 if (index >= 0 && index < this.items.length) {
3652 option = this.options[this.items[index]];
3653 if (this.deleteSelection(e)) {
3654 this.setTextboxValue(options.text.apply(this, [option]));
3655 this.refreshOptions(true);
3661 return original.apply(this, arguments);