-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.autocomplete.multi.js
More file actions
421 lines (370 loc) · 14.9 KB
/
Copy pathjquery.autocomplete.multi.js
File metadata and controls
421 lines (370 loc) · 14.9 KB
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
/**
* jQuery Autocomplete extension for multi-selection
* @author Andrew Richardson
*/
(function($){
var KEY = {
BACKSPACE: 8,
LEFT: 37,
RIGHT: 39,
DELETE: 46
},
NORESULTS = "NORESULTS",
ADDNEW = "ADDNEW";
/**
* Multi-select Autocomplete Box
*
* Initialization:
* $('select#my-select').autocomplete_multi();
*
* Can be called on any HTML element - the element will be removed from
* the DOM and replaced with an autocomplete edit box. Three common uses:
* 1) (Most common) Replace a <select> element - the options in the
* select will be used to populate the autocomplete suggestions,
* unless a custom "source" option is provided.
*
* 2) Replace a text input - the initial value of the text input
* should be a JSON string in the format expected by Autocomplete:
* [{'label': 'item1', 'value': 1}, {'label': 'item2', 'value': 2}]
*
* 3) Replace any element and specify a custom "source" option
* (just like the regular Autocomplete widget).
*
* Options:
* excludeDuplicates - don't allow the same item to be selected twice
* sortable - allow elements to be reordered after they are added
* placeholder - hint text to show in the edit field
* inputWidth - width of the edit field
* noResultsText - text to display when no results are found
* addNewText - text for the "Add new" option (when enabled)
* maxItems - maximum items that can be selected
*
* Callbacks:
* renderItem(item)
* Receives an item in the format {'label': 'item1', 'value': 1}
* Should return an HTML element representing the item in the
* Autocomplete list.
*
* addNew(text, callback)
* If defined, enables the "Add new" option in the autocomplete list.
* When that option is selected, this method will be invoked with the
* text currently entered in the edit box.
* That text can be used to populate a form or dialog allowing the
* user to actually create the new item. Once created, this method
* should invoke callback(item), where item is in the format
* {'label': 'item1', 'value': 1}. The item will then be added to
* the Autocomplete list.
*
* Methods:
* add(item) - add a new bit for the given item into the control
* remove(bit) - remove the given bit (DOM element) from the control
* removeAll() - remove all bits from the control
* clearInput() - clear the text in the edit box
* focusBit(bit) - set focus to the specified bit (DOM element)
*/
$.widget("ui.autocomplete_multi", {
options: {
// Standard autocomplete options
autoFocus: true,
minLength: 1,
delay: 400,
/* most other standard Autocomplete options are
supported and will be passed through */
// Custom options
excludeDuplicates: true,
sortable: false,
placeholder: "",
inputWidth: 50,
noResultsText: "No results",
addNewText: "Add new...",
maxItems: null,
// Standard autocomplete callbacks
focus: function(){ return false; },
// Custom callbacks
// (default behavior for each of these is defined below)
renderItem: null,
addNew: null
},
_create: function() {
var self = this, o = self.options, el = self.element,
choices, initialVal;
// Hide the existing form element and save its name
self.name = el.attr('name');
el.removeAttr('name').hide();
el.data("autocomplete_multi", self);
if(el.is(':input')) {
choices = {};
initialVal = [];
// If using a select box and no custom source was provided, read
// in the options to use as source data
if(el.is('select')) {
el.find('option').each(function(){
var opt = $(this),
value = opt.val();
choices[value] = {
value: value,
label: opt.html()
};
if(value && opt.is(':selected')) {
initialVal.push(value);
}
});
if(!o.source) {
o.source = [];
for(var id in choices) o.source.push(choices[id]);
}
}
// If using a text input, try to parse the initial value as JSON
else {
try {
var json = $.parseJSON(el.val());
for(var i=0; i<json.length; i++) {
initialVal.push(json[i].value);
choices[json[i].value] = json[i];
}
} catch(e) {
}
}
}
// Create all the necessary elements
self.wrapper = $("<ul class='ui-autocomplete-multi'/>");
self.input = $("<input type='text'/>").width(o.inputWidth);
self.loading = $("<li class='ui-autocomplete-multi-loading'/>");
self.bit = $("<li class='ui-autocomplete-multi-bit'/>")
.append("<span class='ui-icon ui-icon-close'/>")
.append("<span class='ui-autocomplete-multi-bit-text'/>");
self.inputBit = $("<li class='ui-autocomplete-multi-input-bit'/>");
el.focus(function(){ self.input.focus(); });
// Pull in default callbacks
if(!o.renderItem) o.renderItem = self._renderItem;
// search callback (show the loading graphic when searching)
var custom_search = o.search ? o.search : null;
o.search = function(event, ui) {
self.loading.show();
if(custom_search) return custom_search(event, ui);
};
// Default select callback (can be overridden)
var customSelect = o.select || function(event, ui){
if(self.add(ui.item)) {
self.input.val("");
}
};
o.select = function(event, ui) {
if(ui.item.value == ADDNEW) {
// Fire the addNew() callback
o.addNew(self.input.val(), function(item){
ui.item = item;
customSelect.call(el, event, ui);
});
} else {
// By default, just add the new item
customSelect.call(el, event, ui);
}
return false;
}
// Format the control
self.wrapper
.insertAfter(el)
.append(self.loading.hide())
.append(self.inputBit.append(self.input))
.append("<li style='display: block; clear: both;'/>")
.click(function(){ self.focusBit(null); self.input.focus(); });
// Position the autocomplete results
o.appendTo = self.wrapper;
o.position = {my: "left top", at: "left bottom", of: self.wrapper};
// Initialize autocomplete box
self.input.autocomplete(o);
var autocomplete = self.input.data("ui-autocomplete");
self._replaceSourceCallback();
// keypress callbacks
self.wrapper.keydown(function(event){
self._keyDown(event);
});
self.input.keydown(function(event){
self._keyDownInput(event);
});
// Apply the custom item rendering
autocomplete._renderItem = function(ul, item) {
var li;
if(item.value == NORESULTS) {
// Bypass custom rendering for the "No results" item
li = self._renderItem(item);
li.addClass("ui-autocomplete-multi-noresults");
} else if(item.value == ADDNEW) {
// Bypass custom rendering for the "Add new" item
li = self._renderItem(item);
li.addClass("ui-autocomplete-multi-addnew");
} else {
li = o.renderItem.call(self, item);
}
ul.append(li);
return li;
};
// Insert initial values
if(choices && initialVal) {
for(var i=0; i<initialVal.length; i++) {
self.add(choices[initialVal[i]]);
}
}
// Initialize sorting
if(o.sortable) {
self.wrapper.sortable({ items: '.ui-autocomplete-multi-bit' });
}
// Show hint text
if(o.placeholder) {
self.input.attr('placeholder', o.placeholder);
}
},
// Return the control to normal
destroy: function() {
this.wrapper.remove();
this.element.show();
},
// Get/set options
option: function(name, value) {
this.input.autocomplete('option', name, value);
if(name == "source") {
this._replaceSourceCallback();
}
},
// Add an item to the box
add: function(item) {
var self = this, o = self.options;
// Check for the "no results" item
if(item.value == NORESULTS) return false;
// Make sure the item doesn't already exist
if(o.excludeDuplicates) {
self._getBits().each(function(){
var item2 = $(this).data('autocomplete-item');
if(item.value == item2.value) {
self.remove(this);
}
});
}
// Make sure not to go over the max
if(o.maxItems) {
bitCount = self._getBits().length;
if(bitCount >= o.maxItems) return false;
else if(bitCount == o.maxItems - 1) self.inputBit.hide();
}
// Insert a bit for the selected item
self.bit.clone()
.insertBefore(self.inputBit)
.data('autocomplete-item', item)
.click(function(event){
self.focusBit(this);
self.input.focus();
event.stopPropagation();
})
.children('.ui-autocomplete-multi-bit-text')
.html(item.label)
.end()
.children('.ui-icon-close').click(function(){
self.remove($(this).parent());
}).end()
.append(
$('<input type="hidden" />')
.attr('name', self.name)
.val(item.value)
);
self.focusBit(null);
return true;
},
// Remove a bit from the box
remove: function(bit) {
var self = this;
bit = $(bit);
if(bit.hasClass('ui-state-focus')) {
var newFocus = bit.prev();
if(!newFocus.length) newFocus = bit.next();
self.focusBit(newFocus);
}
bit.remove();
self.inputBit.show();
},
// Remove all bits from the box
removeAll: function() {
this._getBits().remove();
this.inputBit.show();
},
clearInput: function() {
this.input.val('');
},
// Select the indicated bit
focusBit: function(bit) {
var self = this, bits = self._getBits();
bit = $(bit);
bits.removeClass('ui-state-focus');
if(bit.length > 0 && bit[0] != self.inputBit[0]) {
bit.addClass('ui-state-focus');
}
},
// Add on to the user-defined source callback
_replaceSourceCallback: function() {
var self = this,
autocomplete = self.input.data("ui-autocomplete"),
sourceCallback = autocomplete.source,
o = self.options;
autocomplete.source = function(request, response) {
sourceCallback(request, function(data){
// Hide the loading graphic when search completes
self.loading.hide();
if(!data) data = [];
if(o.addNew) {
// Insert the the "Add new" item
data.push({ label: o.addNewText, value: ADDNEW });
} else if(data.length == 0) {
// Insert the "No results" text
data.push({ label: o.noResultsText, value: NORESULTS });
}
response(data);
});
};
},
// Get all bits currently added
_getBits: function() {
return this.wrapper.children('.ui-autocomplete-multi-bit');
},
// Render an item in the results list (can be overridden)
_renderItem: function(item) {
return $("<li/>")
.data("item.autocomplete", item)
.append(item.label)
.wrapInner("<a/>");
},
// Handle keypresses in the input box
_keyDownInput: function(event) {
// Unless the box is empty, stop keys from propagating upwards
var self = this, val = self.input.val();
if(val != "") event.stopPropagation();
},
// Handle keypresses
_keyDown: function(event) {
var self = this, curBit = self.wrapper.children('.ui-state-focus');
switch(event.keyCode) {
case KEY.BACKSPACE:
// Backspace - move backward and delete bits
if(curBit.length) self.remove(curBit);
else {
self.focusBit(self.inputBit.prev());
event.preventDefault();
}
break;
case KEY.DELETE:
// Delete - delete bits
if(curBit.length) self.remove(curBit);
break;
case KEY.LEFT:
// Left - select previous bit
if(!curBit.length) self.focusBit(self.inputBit.prev());
else self.focusBit(curBit.prev());
break;
case KEY.RIGHT:
// Right - select next bit
if(!curBit.length) self.focusBit(self._getBits().eq(0));
else self.focusBit(curBit.next());
break;
}
}
});
})(jQuery);