forked from JayDevOps/magicsuggest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magicsuggest.js
1565 lines (1392 loc) · 58.5 KB
/
magicsuggest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Multiple Selection Component for Bootstrap
* Check nicolasbize.github.io/magicsuggest/ for latest updates.
*
* Author: Nicolas Bize
* Created: Feb 8th 2013
* Last Updated: Oct 16th 2014
* Version: 2.1.4
* Licence: MagicSuggest is licenced under MIT licence (http://opensource.org/licenses/MIT)
*/
(function($)
{
"use strict";
var MagicSuggest = function(element, options)
{
var ms = this;
/**
* Initializes the MagicSuggest component
*/
var defaults = {
/********** CONFIGURATION PROPERTIES ************/
/**
* Restricts or allows the user to validate typed entries.
* Defaults to true.
*/
allowFreeEntries: true,
/**
* Restricts or allows the user to add the same entry more than once
* Defaults to false.
*/
allowDuplicates: false,
/**
* Additional config object passed to each $.ajax call
*/
ajaxConfig: {},
/**
* If a single suggestion comes out, it is preselected.
*/
autoSelect: true,
/**
* Auto select the first matching item with multiple items shown
*/
selectFirst: false,
/**
* Allow customization of query parameter
*/
queryParam: 'query',
/**
* A function triggered just before the ajax request is sent, similar to jQuery
*/
beforeSend: function(){ },
/**
* A custom CSS class to apply to the field's underlying element.
*/
cls: '',
/**
* JSON Data source used to populate the combo box. 3 options are available here:
* No Data Source (default)
* When left null, the combo box will not suggest anything. It can still enable the user to enter
* multiple entries if allowFreeEntries is * set to true (default).
* Static Source
* You can pass an array of JSON objects, an array of strings or even a single CSV string as the
* data source.For ex. data: [* {id:0,name:"Paris"}, {id: 1, name: "New York"}]
* You can also pass any json object with the results property containing the json array.
* Url
* You can pass the url from which the component will fetch its JSON data.Data will be fetched
* using a POST ajax request that will * include the entered text as 'query' parameter. The results
* fetched from the server can be:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
* Function
* You can pass a function which returns an array of JSON objects (ex: [{id:...,name:...},{...}])
* The function can return the JSON data or it can use the first argument as function to handle the data.
* Only one (callback function or return value) is needed for the function to succeed.
* See the following example:
* function (response) { var myjson = [{name: 'test', id: 1}]; response(myjson); return myjson; }
*/
data: null,
/**
* Additional parameters to the ajax call
*/
dataUrlParams: {},
/**
* Start the component in a disabled state.
*/
disabled: false,
/**
* Name of JSON object property that defines the disabled behaviour
*/
disabledField: null,
/**
* Name of JSON object property displayed in the combo list
*/
displayField: 'name',
/**
* Set to false if you only want mouse interaction. In that case the combo will
* automatically expand on focus.
*/
editable: true,
/**
* Set starting state for combo.
*/
expanded: false,
/**
* Automatically expands combo on focus.
*/
expandOnFocus: false,
/**
* JSON property by which the list should be grouped
*/
groupBy: null,
/**
* Set to true to hide the trigger on the right
*/
hideTrigger: false,
/**
* Set to true to highlight search input within displayed suggestions
*/
highlight: true,
/**
* A custom ID for this component
*/
id: null,
/**
* A class that is added to the info message appearing on the top-right part of the component
*/
infoMsgCls: '',
/**
* Additional parameters passed out to the INPUT tag. Enables usage of AngularJS's custom tags for ex.
*/
inputCfg: {},
/**
* The class that is applied to show that the field is invalid
*/
invalidCls: 'ms-inv',
/**
* Set to true to filter data results according to case. Useless if the data is fetched remotely
*/
matchCase: false,
/**
* Once expanded, the combo's height will take as much room as the # of available results.
* In case there are too many results displayed, this will fix the drop down height.
*/
maxDropHeight: 290,
/**
* Defines how long the user free entry can be. Set to null for no limit.
*/
maxEntryLength: null,
/**
* A function that defines the helper text when the max entry length has been surpassed.
*/
maxEntryRenderer: function(v) {
return 'Please reduce your entry by ' + v + ' character' + (v > 1 ? 's':'');
},
/**
* The maximum number of results displayed in the combo drop down at once.
*/
maxSuggestions: null,
/**
* The maximum number of items the user can select if multiple selection is allowed.
* Set to null to remove the limit.
*/
maxSelection: 10,
/**
* A function that defines the helper text when the max selection amount has been reached. The function has a single
* parameter which is the number of selected elements.
*/
maxSelectionRenderer: function(v) {
return 'You cannot choose more than ' + v + ' item' + (v > 1 ? 's':'');
},
/**
* The method used by the ajax request.
*/
method: 'POST',
/**
* The minimum number of characters the user must type before the combo expands and offers suggestions.
*/
minChars: 0,
/**
* A function that defines the helper text when not enough letters are set. The function has a single
* parameter which is the difference between the required amount of letters and the current one.
*/
minCharsRenderer: function(v) {
return 'Please type ' + v + ' more character' + (v > 1 ? 's':'');
},
/**
* Whether or not sorting / filtering should be done remotely or locally.
* Use either 'local' or 'remote'
*/
mode: 'local',
/**
* The name used as a form element.
*/
name: null,
/**
* The text displayed when there are no suggestions.
*/
noSuggestionText: 'No suggestions',
/**
* The default placeholder text when nothing has been entered
*/
placeholder: 'Type or click here',
/**
* A function used to define how the items will be presented in the combo
*/
renderer: null,
/**
* Whether or not this field should be required
*/
required: false,
/**
* Set to true to render selection as a delimited string
*/
resultAsString: false,
/**
* Text delimiter to use in a delimited string.
*/
resultAsStringDelimiter: ',',
/**
* Name of JSON object property that represents the list of suggested objects
*/
resultsField: 'results',
/**
* A custom CSS class to add to a selected item
*/
selectionCls: '',
/**
* An optional element replacement in which the selection is rendered
*/
selectionContainer: null,
/**
* Where the selected items will be displayed. Only 'right', 'bottom' and 'inner' are valid values
*/
selectionPosition: 'inner',
/**
* A function used to define how the items will be presented in the tag list
*/
selectionRenderer: null,
/**
* Set to true to stack the selectioned items when positioned on the bottom
* Requires the selectionPosition to be set to 'bottom'
*/
selectionStacked: false,
/**
* Direction used for sorting. Only 'asc' and 'desc' are valid values
*/
sortDir: 'asc',
/**
* name of JSON object property for local result sorting.
* Leave null if you do not wish the results to be ordered or if they are already ordered remotely.
*/
sortOrder: null,
/**
* If set to true, suggestions will have to start by user input (and not simply contain it as a substring)
*/
strictSuggest: false,
/**
* Custom style added to the component container.
*/
style: '',
/**
* If set to true, the combo will expand / collapse when clicked upon
*/
toggleOnClick: false,
/**
* Amount (in ms) between keyboard registers.
*/
typeDelay: 400,
/**
* If set to true, tab won't blur the component but will be registered as the ENTER key
*/
useTabKey: false,
/**
* If set to true, using comma will validate the user's choice
*/
useCommaKey: true,
/**
* Determines whether or not the results will be displayed with a zebra table style
*/
useZebraStyle: false,
/**
* initial value for the field
*/
value: null,
/**
* name of JSON object property that represents its underlying value
*/
valueField: 'id',
/**
* regular expression to validate the values against
*/
vregex: null,
/**
* type to validate against
*/
vtype: null
};
var conf = $.extend({},options);
var cfg = $.extend(true, {}, defaults, conf);
/********** PUBLIC METHODS ************/
/**
* Add one or multiple json items to the current selection
* @param items - json object or array of json objects
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
this.addToSelection = function(items, isSilent)
{
if (!cfg.maxSelection || _selection.length < cfg.maxSelection) {
if (!$.isArray(items)) {
items = [items];
}
var valuechanged = false;
$.each(items, function(index, json) {
if (cfg.allowDuplicates || $.inArray(json[cfg.valueField], ms.getValue()) === -1) {
_selection.push(json);
valuechanged = true;
}
});
if(valuechanged === true) {
self._renderSelection();
this.empty();
if (isSilent !== true) {
$(this).trigger('selectionchange', [this, this.getSelection()]);
}
}
}
this.input.attr('placeholder', (cfg.selectionPosition === 'inner' && this.getValue().length > 0) ? '' : cfg.placeholder);
};
/**
* Clears the current selection
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
this.clear = function(isSilent)
{
this.removeFromSelection(_selection.slice(0), isSilent); // clone array to avoid concurrency issues
};
/**
* Collapse the drop down part of the combo
*/
this.collapse = function()
{
if (cfg.expanded === true) {
this.combobox.detach();
cfg.expanded = false;
$(this).trigger('collapse', [this]);
}
};
/**
* Set the component in a disabled state.
*/
this.disable = function()
{
this.container.addClass('ms-ctn-disabled');
cfg.disabled = true;
ms.input.attr('disabled', true);
};
/**
* Empties out the combo user text
*/
this.empty = function(){
this.input.val('');
};
/**
* Set the component in a enable state.
*/
this.enable = function()
{
this.container.removeClass('ms-ctn-disabled');
cfg.disabled = false;
ms.input.attr('disabled', false);
};
/**
* Expand the drop drown part of the combo.
*/
this.expand = function()
{
if (!cfg.expanded && (this.input.val().length >= cfg.minChars || this.combobox.children().length > 0)) {
this.combobox.appendTo(this.container);
self._processSuggestions();
cfg.expanded = true;
$(this).trigger('expand', [this]);
}
};
/**
* Retrieve component enabled status
*/
this.isDisabled = function()
{
return cfg.disabled;
};
/**
* Checks whether the field is valid or not
* @return {boolean}
*/
this.isValid = function()
{
var valid = cfg.required === false || _selection.length > 0;
if(cfg.vtype || cfg.vregex){
$.each(_selection, function(index, item){
valid = valid && self._validateSingleItem(item[cfg.valueField]);
});
}
return valid;
};
/**
* Gets the data params for current ajax request
*/
this.getDataUrlParams = function()
{
return cfg.dataUrlParams;
};
/**
* Gets the name given to the form input
*/
this.getName = function()
{
return cfg.name;
};
/**
* Retrieve an array of selected json objects
* @return {Array}
*/
this.getSelection = function()
{
return _selection;
};
/**
* Retrieve the current text entered by the user
*/
this.getRawValue = function(){
return ms.input.val();
};
/**
* Retrieve an array of selected values
*/
this.getValue = function()
{
return $.map(_selection, function(o) {
return o[cfg.valueField];
});
};
/**
* Remove one or multiples json items from the current selection
* @param items - json object or array of json objects
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
this.removeFromSelection = function(items, isSilent)
{
if (!$.isArray(items)) {
items = [items];
}
var valuechanged = false;
$.each(items, function(index, json) {
var i = $.inArray(json[cfg.valueField], ms.getValue());
if (i > -1) {
_selection.splice(i, 1);
valuechanged = true;
}
});
if (valuechanged === true) {
self._renderSelection();
if(isSilent !== true){
$(this).trigger('selectionchange', [this, this.getSelection()]);
}
if(cfg.expandOnFocus){
ms.expand();
}
if(cfg.expanded) {
self._processSuggestions();
}
}
this.input.attr('placeholder', (cfg.selectionPosition === 'inner' && this.getValue().length > 0) ? '' : cfg.placeholder);
};
/**
* Get current data
*/
this.getData = function(){
return _cbData;
};
/**
* Set up some combo data after it has been rendered
* @param data
*/
this.setData = function(data){
cfg.data = data;
self._processSuggestions();
};
/**
* Sets the name for the input field so it can be fetched in the form
* @param name
*/
this.setName = function(name){
cfg.name = name;
if(name){
cfg.name += name.indexOf('[]') > 0 ? '' : '[]';
}
if(ms._valueContainer){
$.each(ms._valueContainer.children(), function(i, el){
el.name = cfg.name;
});
}
};
/**
* Sets the current selection with the JSON items provided
* @param items
*/
this.setSelection = function(items){
this.clear();
this.addToSelection(items);
};
/**
* Sets a value for the combo box. Value must be an array of values with data type matching valueField one.
* @param data
*/
this.setValue = function(values)
{
var items = [];
$.each(values, function(index, value) {
// first try to see if we have the full objects from our data set
var found = false;
$.each(_cbData, function(i,item){
if(item[cfg.valueField] == value){
items.push(item);
found = true;
return false;
}
});
if(!found){
if(typeof(value) === 'object'){
items.push(value);
} else {
var json = {};
json[cfg.valueField] = value;
json[cfg.displayField] = value;
items.push(json);
}
}
});
if(items.length > 0) {
this.addToSelection(items);
}
};
/**
* Sets data params for subsequent ajax requests
* @param params
*/
this.setDataUrlParams = function(params)
{
cfg.dataUrlParams = $.extend({},params);
};
/********** PRIVATE ************/
var _selection = [], // selected objects
_comboItemHeight = 0, // height for each combo item.
_timer,
_hasFocus = false,
_groups = null,
_cbData = [],
_ctrlDown = false,
KEYCODES = {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
CTRL: 17,
ESC: 27,
SPACE: 32,
UPARROW: 38,
DOWNARROW: 40,
COMMA: 188
};
var self = {
/**
* Empties the result container and refills it with the array of json results in input
* @private
*/
_displaySuggestions: function(data) {
ms.combobox.show();
ms.combobox.empty();
var resHeight = 0, // total height taken by displayed results.
nbGroups = 0;
if(_groups === null) {
self._renderComboItems(data);
resHeight = _comboItemHeight * data.length;
}
else {
for(var grpName in _groups) {
nbGroups += 1;
$('<div/>', {
'class': 'ms-res-group',
html: grpName
}).appendTo(ms.combobox);
self._renderComboItems(_groups[grpName].items, true);
}
var _groupItemHeight = ms.combobox.find('.ms-res-group').outerHeight();
if(_groupItemHeight !== null) {
var tmpResHeight = nbGroups * _groupItemHeight;
resHeight = (_comboItemHeight * data.length) + tmpResHeight;
} else {
resHeight = _comboItemHeight * (data.length + nbGroups);
}
}
if(resHeight < ms.combobox.height() || resHeight <= cfg.maxDropHeight) {
ms.combobox.height(resHeight);
}
else if(resHeight >= ms.combobox.height() && resHeight > cfg.maxDropHeight) {
ms.combobox.height(cfg.maxDropHeight);
}
if(data.length === 1 && cfg.autoSelect === true) {
ms.combobox.children().filter(':not(.ms-res-item-disabled):last').addClass('ms-res-item-active');
}
if (cfg.selectFirst === true) {
ms.combobox.children().filter(':not(.ms-res-item-disabled):first').addClass('ms-res-item-active');
}
if(data.length === 0 && ms.getRawValue() !== "") {
var noSuggestionText = cfg.noSuggestionText.replace(/\{\{.*\}\}/, ms.input.val());
self._updateHelper(noSuggestionText);
ms.collapse();
}
// When free entry is off, add invalid class to input if no data matches
if(cfg.allowFreeEntries === false) {
if(data.length === 0) {
$(ms.input).addClass(cfg.invalidCls);
ms.combobox.hide();
} else {
$(ms.input).removeClass(cfg.invalidCls);
}
}
},
/**
* Returns an array of json objects from an array of strings.
* @private
*/
_getEntriesFromStringArray: function(data) {
var json = [];
$.each(data, function(index, s) {
var entry = {};
entry[cfg.displayField] = entry[cfg.valueField] = $.trim(s);
json.push(entry);
});
return json;
},
/**
* Replaces html with highlighted html according to case
* @param html
* @private
*/
_highlightSuggestion: function(html) {
var q = ms.input.val();
//escape special regex characters
var specialCharacters = ['^', '$', '*', '+', '?', '.', '(', ')', ':', '!', '|', '{', '}', '[', ']'];
$.each(specialCharacters, function (index, value) {
q = q.replace(value, "\\" + value);
})
if(q.length === 0) {
return html; // nothing entered as input
}
var glob = cfg.matchCase === true ? 'g' : 'gi';
return html.replace(new RegExp('(' + q + ')(?!([^<]+)?>)', glob), '<em>$1</em>');
},
/**
* Moves the selected cursor amongst the list item
* @param dir - 'up' or 'down'
* @private
*/
_moveSelectedRow: function(dir) {
if(!cfg.expanded) {
ms.expand();
}
var list, start, active, scrollPos;
list = ms.combobox.find(".ms-res-item:not(.ms-res-item-disabled)");
if(dir === 'down') {
start = list.eq(0);
}
else {
start = list.filter(':last');
}
active = ms.combobox.find('.ms-res-item-active:not(.ms-res-item-disabled):first');
if(active.length > 0) {
if(dir === 'down') {
start = active.nextAll('.ms-res-item:not(.ms-res-item-disabled)').first();
if(start.length === 0) {
start = list.eq(0);
}
scrollPos = ms.combobox.scrollTop();
ms.combobox.scrollTop(0);
if(start[0].offsetTop + start.outerHeight() > ms.combobox.height()) {
ms.combobox.scrollTop(scrollPos + _comboItemHeight);
}
}
else {
start = active.prevAll('.ms-res-item:not(.ms-res-item-disabled)').first();
if(start.length === 0) {
start = list.filter(':last');
ms.combobox.scrollTop(_comboItemHeight * list.length);
}
if(start[0].offsetTop < ms.combobox.scrollTop()) {
ms.combobox.scrollTop(ms.combobox.scrollTop() - _comboItemHeight);
}
}
}
list.removeClass("ms-res-item-active");
start.addClass("ms-res-item-active");
},
/**
* According to given data and query, sort and add suggestions in their container
* @private
*/
_processSuggestions: function(source) {
var json = null, data = source || cfg.data;
if(data !== null) {
if(typeof(data) === 'function'){
data = data.call(ms, ms.getRawValue());
}
if(typeof(data) === 'string') { // get results from ajax
$(ms).trigger('beforeload', [ms]);
var queryParams = {}
queryParams[cfg.queryParam] = ms.input.val();
var params = $.extend(queryParams, cfg.dataUrlParams);
$.ajax($.extend({
type: cfg.method,
url: data,
data: params,
beforeSend: cfg.beforeSend,
success: function(asyncData){
json = typeof(asyncData) === 'string' ? JSON.parse(asyncData) : asyncData;
self._processSuggestions(json);
$(ms).trigger('load', [ms, json]);
if(self._asyncValues){
ms.setValue(typeof(self._asyncValues) === 'string' ? JSON.parse(self._asyncValues) : self._asyncValues);
self._renderSelection();
delete(self._asyncValues);
}
},
error: function(){
throw("Could not reach server");
}
}, cfg.ajaxConfig));
return;
} else { // results from local array
if(data.length > 0 && typeof(data[0]) === 'string') { // results from array of strings
_cbData = self._getEntriesFromStringArray(data);
} else { // regular json array or json object with results property
_cbData = data[cfg.resultsField] || data;
}
}
var sortedData = cfg.mode === 'remote' ? _cbData : self._sortAndTrim(_cbData);
self._displaySuggestions(self._group(sortedData));
}
},
/**
* Render the component to the given input DOM element
* @private
*/
_render: function(el) {
ms.setName(cfg.name); // make sure the form name is correct
// holds the main div, will relay the focus events to the contained input element.
ms.container = $('<div/>', {
'class': 'ms-ctn form-control ' + (cfg.resultAsString ? 'ms-as-string ' : '') + cfg.cls +
($(el).hasClass('input-lg') ? ' input-lg' : '') +
($(el).hasClass('input-sm') ? ' input-sm' : '') +
(cfg.disabled === true ? ' ms-ctn-disabled' : '') +
(cfg.editable === true ? '' : ' ms-ctn-readonly') +
(cfg.hideTrigger === false ? '' : ' ms-no-trigger'),
style: cfg.style,
id: cfg.id
});
ms.container.on('focus', $.proxy(handlers._onFocus, this));
ms.container.on('blur', $.proxy(handlers._onBlur, this));
ms.container.on('keydown', $.proxy(handlers._onKeyDown, this));
ms.container.on('keyup', $.proxy(handlers._onKeyUp, this));
// holds the input field
ms.input = $('<input/>', $.extend({
type: 'text',
'class': cfg.editable === true ? '' : ' ms-input-readonly',
readonly: !cfg.editable,
placeholder: cfg.placeholder,
disabled: cfg.disabled
}, cfg.inputCfg));
ms.input.on('focus', $.proxy(handlers._onInputFocus, this));
ms.input.on('click', $.proxy(handlers._onInputClick, this));
// holds the suggestions. will always be placed on focus
ms.combobox = $('<div/>', {
'class': 'ms-res-ctn dropdown-menu'
}).height(cfg.maxDropHeight);
// bind the onclick and mouseover using delegated events (needs jQuery >= 1.7)
ms.combobox.on('click', 'div.ms-res-item', $.proxy(handlers._onComboItemSelected, this));
ms.combobox.on('mouseover', 'div.ms-res-item', $.proxy(handlers._onComboItemMouseOver, this));
if(cfg.selectionContainer){
ms.selectionContainer = cfg.selectionContainer;
$(ms.selectionContainer).addClass('ms-sel-ctn');
} else {
ms.selectionContainer = $('<div/>', {
'class': 'ms-sel-ctn'
});
}
ms.selectionContainer.on('click', $.proxy(handlers._onFocus, this));
if(cfg.selectionPosition === 'inner' && !cfg.selectionContainer) {
ms.selectionContainer.append(ms.input);
}
else {
ms.container.append(ms.input);
}
ms.helper = $('<span/>', {
'class': 'ms-helper ' + cfg.infoMsgCls
});
self._updateHelper();
ms.container.append(ms.helper);
// Render the whole thing
$(el).replaceWith(ms.container);
if(!cfg.selectionContainer){
switch(cfg.selectionPosition) {
case 'bottom':
ms.selectionContainer.insertAfter(ms.container);
if(cfg.selectionStacked === true) {
ms.selectionContainer.width(ms.container.width());
ms.selectionContainer.addClass('ms-stacked');
}
break;
case 'right':
ms.selectionContainer.insertAfter(ms.container);
ms.container.css('float', 'left');
break;
default:
ms.container.append(ms.selectionContainer);
break;
}
}
// holds the trigger on the right side
if(cfg.hideTrigger === false) {
ms.trigger = $('<div/>', {
'class': 'ms-trigger',
html: '<div class="ms-trigger-ico"></div>'
});
ms.trigger.on('click', $.proxy(handlers._onTriggerClick, this));
ms.container.append(ms.trigger);
}
$(window).on('resize', $.proxy(handlers._onWindowResized, this));
// do not perform an initial call if we are using ajax unless we have initial values
if(cfg.value !== null || cfg.data !== null){
if(typeof(cfg.data) === 'string'){
self._asyncValues = cfg.value;
self._processSuggestions();
} else {
self._processSuggestions();
if(cfg.value !== null){
ms.setValue(cfg.value);
self._renderSelection();
}
}
}
$("body").on('click', function(e) {
if(ms.container.hasClass('ms-ctn-focus') &&
ms.container.has(e.target).length === 0 &&
e.target.className.indexOf('ms-res-item') < 0 &&
e.target.className.indexOf('ms-close-btn') < 0 &&
ms.container[0] !== e.target) {
handlers._onBlur();
}
});
if(cfg.expanded === true) {
cfg.expanded = false;
ms.expand();
}
},
/**
* Renders each element within the combo box
* @private
*/
_renderComboItems: function(items, isGrouped) {
var ref = this, html = '';
$.each(items, function(index, value) {
var displayed = cfg.renderer !== null ? cfg.renderer.call(ref, value) : value[cfg.displayField];
var disabled = cfg.disabledField !== null && value[cfg.disabledField] === true;
var resultItemEl = $('<div/>', {
'class': 'ms-res-item ' + (isGrouped ? 'ms-res-item-grouped ':'') +
(disabled ? 'ms-res-item-disabled ':'') +