-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.js
483 lines (376 loc) · 12.4 KB
/
autocomplete.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
// Super 1337 Autocompletion class
var Autocomplete = function(root) {
this.root = $(root);
this.initialize();
}
Autocomplete.prototype = {
// constructor
initialize: function() {
this.selectedValue = this.root.val();
if(this.root.attr('tagName') == 'INPUT' && this.root.attr('type') == 'text') {
this.input = this.root;
this.freeInput = true;
} else if(this.root.attr('tagName') == 'SELECT') {
// create new input field for autocompletion
this.freeInput = false;
this.input = this.createInput();
this.input.attr("autocomplete", "off");
// remove from DOM
this.root.remove();
// multiselect?
this.multiselect = this.root.attr('multiple');
// show details?
this.showDetails = this.root.attr('data-show-details');
// add a list with multi vals
if(this.multiselect || this.showDetails) {
if(this.multiselect) {
// create empty array
hidden = $('<input type="hidden" />');
hidden.attr('id', this.root.attr('id') + '_val_empty');
hidden.attr('name', this.root.attr('name'));
hidden.val('');
this.input.after(hidden);
}
// add a div
this.multiselectListContainer = this.createMultiselectListContainer();
// and a ul
this.multiselectList = this.createMultiselectList();
this.itemUrl = this.root.attr('data-item-url');
}
// set default texts
this.setDefaultVals();
}
// create dropdown and hidden fields
this.dropdown = this.createDropdown();
if(!this.multiselect && !this.freeInput) {
this.hiddenField = this.createHiddenField();
this.hiddenField.val(this.selectedValue);
}
this.autocompleteUrl = this.root.attr('data-autocomplete-url');
this.input[0].autocomplete = this;
// add keypress listener
this.input.keypress(this.bind(this.handleKeypress));
this.input.click(this.bind(this.handleInputClick));
this.input.blur(this.bind(this.handleBlur));
// finally, check the multivalues and autofill them
if(this.multiselect || this.showDetails) {
this.updateMultiVals();
if(this.multiselect) this.updateMultiValHiddenField();
}
this.input.autocomplete = this;
},
addSelectedValue: function(id) {
if(this.multiselect) {
var vals = this.selectedValue;
if(!vals) vals = [];
vals.push(id);
this.selectedValue = vals;
this.updateMultiValHiddenField();
this.input.val('');
}
this.root.val(this.selectedValue);
// retrieve & show all current selected items
if(this.multiselect || this.showDetails)
this.updateMultiVals();
},
// creates a multiselect list container
createMultiselectListContainer: function() {
var container = $('<div></div>');
container.attr('id', this.root.attr('id') + '_value_list_container');
container.attr('className', 'autocomplete_value_list');
// insert dropdown after textfield
this.input.after(container);
return container;
},
// create a UL for the multiselector
createMultiselectList: function() {
var list = $('<ul></ul>');
list.attr('id', this.root.attr('id') + '_value_list');
this.multiselectListContainer.append(list);
return list;
},
// requests the HTML for the multiselectbox list
updateMultiVals: function() {
var i = 0;
var vals = this.selectedValue;
if(!vals) vals = [];
if(typeof(vals) == 'string' || typeof(vals) == 'number') vals = [vals];
if(!this.multiselect && this.showDetails && vals[0] && this.multiselectList.find('li[rel]').length > 0) {
var firstItem = $(this.multiselectList.find('li')[0]);
if(firstItem.attr('rel') != vals[0]) {
firstItem.remove();
}
}
// loop every selected val
for(i = 0; i < vals.length; i++) {
// do already have a list item with this ID?
if(this.multiselectList.find('li[rel="' + vals[i] + '"]').length == 0) {
// no, so go request it!
$.getJSON(this.itemUrl.replace('%', vals[i]).replace('%25', vals[i]), this.bind(this.handleUpdateMultiValsResponse));
}
}
},
// is called when load for requestMultiVals is complete
// NOTE: this thing only receives ONE item
handleUpdateMultiValsResponse: function(data) {
// we have received one item, good!
var item;
var i = 0;
var list;
// valid data?
if(data && this.multiselectList.find('li[rel="' + data.id + '"]').length == 0) {
// yes!
// add this to the unsorted list
item = $('<li></li>');
item.append('<h3>' + data.name + '</h3>');
if(data.extra && data.extra.length > 0) {
table = $('<table></table>');
for(i = 0; i < data.extra.length; i++) {
table.append('<tr><th>' + data.extra[i][0] + '</th><td>' + data.extra[i][1] + '</td></tr>');
}
item.append(table);
}
item.attr('rel', data.id);
if(this.multiselect)
item.click(this.bind(this.handleMultiValItemClick));
// add to list
this.multiselectList.append(item);
}
},
updateMultiValHiddenField: function() {
var i = 0;
var values = this.selectedValue;
var hidden;
if(!values) values = [];
for(i = 0; i < values.length; i++) {
if($('input#' + this.root.attr('id') + '_val_' + values[i]).length == 0) {
hidden = $('<input type="hidden" />');
hidden.attr('id', this.root.attr('id') + '_val_' + values[i]);
hidden.attr('name', this.root.attr('name'));
hidden.val(values[i]);
this.input.after(hidden);
}
}
},
// catches the click event on a multival item
handleMultiValItemClick: function(event) {
// remove from values
var item = $(event.currentTarget);
var values = [];
var newValues = [];
var hidden;
var i = 0;
// remove from values
values = this.selectedValue;
for(i = 0; i < values.length; i++) {
if(values[i] != item.attr('rel'))
newValues.push(values[i]);
}
// set new array
this.selectedValue = newValues;
this.root.val(this.selectedValue);
// also remove hidden field!
hidden = $('input#' + this.root.attr('id') + '_val_' + item.attr('rel'));
if(hidden) {
hidden.remove();
hidden = null;
}
item.remove();
item = null;
},
// returns the ids in a string (joined with a comma)
getMultipleVals: function() {
return this.selectedValue.join(',');
},
setDefaultVals: function() {
// set default texts
if(this.root.attr('tagName') == 'SELECT') {
if(this.multiselect) {
// something...
} else {
this.input.val(this.currentSelectboxText());
}
}
},
// bind this obj
bind: function(funct) {
var context = this;
return function() {
return funct.apply(context, arguments);
};
},
// returns the current selected text in a <select> box
currentSelectboxText: function() {
var option = this.root.find('option[value="' + this.selectedValue + '"]');
return option.text();
},
// catches key presses of input
handleKeypress: function(event) {
// cancel dropdown?
if(event.keyCode == 13) {
this.handleKeypressTimer(this);
return false;
}
else if(event.keyCode == 27) {
this.dropdown.hide();
} else {
window.clearTimeout(this.timer);
this.timer = window.setTimeout(this.handleKeypressTimer, 300, this);
}
},
// is dispatched after keypress and after 300 ms.
handleKeypressTimer: function(thisObject) {
thisObject.filter();
},
// handles when a user leaves the text input
handleBlur: function(event) {
window.clearTimeout(this.blurTimer);
this.blurTimer = window.setTimeout(this.bind(this.handleBlurTimer), 150, this);
},
// catches timer for hiding the dropdown
handleBlurTimer: function(event) {
this.dropdown.hide();
},
// displays the dropdown
showDropdown: function() {
window.clearTimeout(this.blurTimer);
this.repositionDropdown();
this.dropdown.show();
this.dropdown.css('width', this.input.innerWidth());
},
// filters autocompletion
filter: function() {
this.input.parent().addClass('loading');
$.getJSON(this.autocompleteUrl.replace('%25', this.input.val()).replace('%', this.input.val()), this.bind(this.handleFilterResponse));
},
// catches response of ajax filter
handleFilterResponse: function(data) {
this.dropdown.empty();
this.input.parent().removeClass('loading');
// only one result?
if(!data || data.length == 0) {
this.input.parent().addClass('not-found')
this.dropdown.hide();
} else {
// build the list!
var i = 0;
var list = $('<ul></ul>');
var item;
var link;
this.input.parent().removeClass('not-found')
// add list to dropdown
this.dropdown.append(list);
// loop every json result
for(i = 0; i < data.length; i++) {
// add to list
item = $('<li></li>');
item.attr('rel', data[i].id);
item.text(data[i].name);
// add clikc
item.click(this.bind(this.handleListItemClick));
list.append(item);
}
// only one possibility?
if(data.length == 1 && this.root.attr('data-autoselect')) {
this.dropdown.hide();
window.clearTimeout(this.timer);
this.timer = window.setTimeout(this.bind(this.handleOnlyOneRowTimer), 300, this);
} else {
this.showDropdown();
}
}
},
handleOnlyOneRowTimer: function(event) {
this.selectItem(this.dropdown.find('ul li'));
},
// catches click on text input field
handleInputClick: function(event) {
this.filter();
},
// selects a link
selectItem: function(item) {
this.dropdown.hide();
if(this.multiselect) {
this.input.parent().removeClass('not-found');
this.input.parent().addClass('found');
var vals = this.selectedValue;
if(!vals) vals = [];
vals.push(item.attr('rel'));
this.selectedValue = vals;
this.updateMultiValHiddenField();
this.input.val('');
} else if(this.freeInput) {
this.selectedValue = item.text();
} else {
this.selectedValue = item.attr('rel');
this.hiddenField.val(item.attr('rel'));
this.input.val(item.text());
}
this.root.val(this.selectedValue);
this.input.focus();
// auto submit?
if(this.root.attr('data-autosubmit') == 'data-autosubmit') {
// submits automaticly the form where the element is placed in
addNoValidationFlag(this.root, this.input.parents('form'));
this.input.parents('form').submit();
}
// retrieve & show all current selected items
if(this.multiselect || this.showDetails)
this.updateMultiVals();
},
// catches click on a item
handleListItemClick: function(event) {
this.selectItem($(event.currentTarget));
},
// positions the dropdown beneath the inputbox
repositionDropdown: function() {
this.dropdown.css({ left: this.input.position().left, top: this.input.position().top + this.input.outerHeight() });
},
// creates a dropdown-box and positions it relative to the root element
createDropdown: function() {
var dd = $('<div></div>');
dd.attr('id', this.root.attr('id') + '_dropdown');
dd.attr('className', 'autocomplete_dropdown');
dd.hide();
// insert dropdown after textfield
this.input.after(dd);
return dd;
},
// transforms the root obj into an input element
createHiddenField: function() {
// create a new root
var hidden = $('<input type="hidden" />');
hidden.attr('id', this.root.attr('id'));
hidden.attr('name', this.root.attr('name'));
// insert after textfield
this.input.after(hidden);
return hidden;
},
// creates an input text field
createInput: function() {
var input = $('<input type="text" />');
var id = this.root.attr('id') + '_input';
input.attr('id', id);
input.attr('name', id);
input.attr('className', 'autocomplete_input');
input.attr('placeholder', this.root.attr('placeholder'));
// insert after root
this.root.after(input);
// check if there is a labe
var label = $("label[for='" + this.root.attr('id') + "']")
if(label.length > 0) {
label.attr('for', this.root.attr('id') + '_input');
}
return input;
}
}
function applyAutocomplete() {
$('.autocomplete').each(function() {
if(!this.autocomplete) {
this.autocomplete = new Autocomplete(this);
}
});
}
$(function() {
applyAutocomplete();
});