-
Notifications
You must be signed in to change notification settings - Fork 194
/
selectpage.js
2543 lines (2391 loc) · 74.5 KB
/
selectpage.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
/**
* @name SelectPage
* @desc Simple and powerful selection plugin
* @file selectpage.js
* @version 2.20
* @author TerryZeng
* @contact https://terryz.github.io/
* @license MIT License
*/
;(function ($) {
'use strict'
/**
* Default options
*/
var defaults = {
/**
* Data source
* @type {string|Object}
*
* string:server side request url address
* Object:JSON array,format:[{a:1,b:2,c:3},{...}]
*/
data: undefined,
/**
* Language ('cn', 'en', 'ja', 'es', 'pt-br')
* @type string
* @default 'cn'
*/
lang: 'cn',
/**
* Multiple select mode(tags)
* @type boolean
* @default false
*/
multiple: false,
/**
* pagination or not
* @type boolean
* @default true
*/
pagination: true,
/**
* Show up menu button
* @type boolean
* @default true
*/
dropButton: true,
/**
* Result list visible size in pagination bar close
* @type number
* @default 10
*/
listSize: 10,
/**
* Show control bar in multiple select mode
* @type boolean
* @default true
*/
multipleControlbar: true,
/**
* Max selected item limited in multiple select mode
* @type number
* @default 0(unlimited)
*/
maxSelectLimit: 0,
/**
* Select result item to close list, work on multiple select mode
* @type boolean
* @default false
*/
selectToCloseList: false,
/**
* Init selected item key, the result will match to option.keyField option
* @type string
*/
initRecord: undefined,
/**
* The table parameter in server side mode
* @type string
*/
dbTable: 'tbl',
/**
* The value field, the value will fill to hidden element
* @type string
* @default 'id'
*/
keyField: 'id',
/**
* The show text field, the text will show to input element or tags(multiple mode)
* @type string
* @default 'name'
*/
showField: 'name',
/**
* Actually used to search field
* @type string
*/
searchField: undefined,
/**
* Search type ('AND' or 'OR')
* @type string
* @default 'AND'
*/
andOr: 'AND',
/**
* Result sort type
* @type array|boolean
* @example
* orderBy : ['id desc']
*/
orderBy: false,
/**
* Page size
* @type number
* @default 10
*/
pageSize: 10,
/**
* Server side request parameters
* @type function
* @return object
* @example params : function(){return {'name':'aa','sex':1};}
*/
params: undefined,
/**
* Custom result list item show text
* @type function
* @param data {object} row data
* @return string
*/
formatItem: undefined,
/**
* Have some highlight item and lost focus, auto select the highlight item
* @type boolean
* @default false
*/
autoFillResult: false,
/**
* Auto select first item in show up result list or search result
* depend on `autoFillResult` option set to true
* @type boolean
* @default false
*/
autoSelectFirst: false,
/**
* Whether clear input element text when enter some keywords to search and no result return
* @type boolean
* @default true
*/
noResultClean: true,
/**
* Select only mode
* @type boolean
*/
selectOnly: false,
/**
* Input to search delay time, work on ajax data source
* @type number
* @default 0.5
*/
inputDelay: 0.5,
/** ---------------------Callback---------------------- */
/**
* Result list item selected callback
* @type function
* @param object - selected item json data
* @param self - plugin object
*/
eSelect: undefined,
/**
* Before result list show up callback, you can do anything prepared
* @param self - plugin object
*/
eOpen: undefined,
/**
* Server side return data convert callback
* @type function
* @param data {object} server side return data
* @param self {object} plugin object
* @return {object} return data format:
* @example
* {
* list : [{name:'aa',sex:1},{name:'bb',sex:1}...],
* totalRow : 100
* }
*/
eAjaxSuccess: undefined,
/**
* Close selected item tag callback (multiple mode)
* @type function
* @param removeCount {number} remove item count
* @param self {object} plugin object
*/
eTagRemove: undefined,
/**
* Clear selected item callback(single select mode)
* @type function
* @param self {object} plugin object
*/
eClear: undefined
}
/**
* SelectPage class definition
* @constructor
* @param {Object} input - input element
* @param {Object} option
*/
var SelectPage = function (input, option) {
this.setOption(option)
this.setLanguage()
this.setCssClass()
this.setProp()
this.setElem(input)
this.setButtonAttrDefault()
this.setInitRecord()
this.eDropdownButton()
this.eInput()
this.eWhole()
}
/**
* Plugin version number
*/
SelectPage.version = '2.20'
/**
* Plugin object cache key
*/
SelectPage.dataKey = 'selectPageObject'
/**
* Options set
* @param {Object} option
*/
SelectPage.prototype.setOption = function (option) {
// use showField by default
option.searchField = option.searchField || option.showField
option.andOr = option.andOr.toUpperCase()
if (option.andOr !== 'AND' && option.andOr !== 'OR') option.andOr = 'AND'
// support multiple field set
var arr = ['searchField']
for (var i = 0; i < arr.length; i++) {
option[arr[i]] = this.strToArray(option[arr[i]])
}
// set multiple order field
// example: [ ['id ASC'], ['name DESC'] ]
if (option.orderBy !== false)
option.orderBy = this.setOrderbyOption(option.orderBy, option.showField)
//close auto fill result and auto select first in multiple mode and select item not close list
if (option.multiple && !option.selectToCloseList) {
option.autoFillResult = false
option.autoSelectFirst = false
}
// show all item when pagination bar close, limited 200
if (!option.pagination) option.pageSize = 200
if ($.type(option.listSize) !== 'number' || option.listSize < 0)
option.listSize = 10
this.option = option
}
/**
* String convert to array
* @param str {string}
* @return {Array}
*/
SelectPage.prototype.strToArray = function (str) {
return str ? str.replace(/[\s ]+/g, '').split(',') : ''
}
/**
* Set order field
* @param {Array} arg_order
* @param {string} arg_field - default sort field
* @return {Array}
*/
SelectPage.prototype.setOrderbyOption = function (arg_order, arg_field) {
var arr = [],
orders = []
if (typeof arg_order === 'object') {
for (var i = 0; i < arg_order.length; i++) {
orders = $.trim(arg_order[i]).split(' ')
if (orders.length) {
arr.push(orders.length === 2 ? orders.concat() : [orders[0], 'ASC'])
}
}
} else {
orders = $.trim(arg_order).split(' ')
arr[0] = orders.length === 2
? orders.concat()
: orders[0].toUpperCase().match(/^(ASC|DESC)$/i)
? [arg_field, orders[0].toUpperCase()]
: [orders[0], 'ASC']
}
return arr
}
/**
* i18n
*/
SelectPage.prototype.setLanguage = function () {
var message, p = this.option
switch (p.lang) {
// German
case 'de':
message = {
add_btn: 'Hinzufügen-Button',
add_title: 'Box hinzufügen',
del_btn: 'Löschen-Button',
del_title: 'Box löschen',
next: 'Nächsten',
next_title: 'Nächsten' + p.pageSize + ' (Pfeil-rechts)',
prev: 'Vorherigen',
prev_title: 'Vorherigen' + p.pageSize + ' (Pfeil-links)',
first_title: 'Ersten (Umschalt + Pfeil-links)',
last_title: 'Letzten (Umschalt + Pfeil-rechts)',
get_all_btn: 'alle (Pfeil-runter)',
get_all_alt: '(Button)',
close_btn: 'Schließen (Tab)',
close_alt: '(Button)',
loading: 'lade...',
loading_alt: '(lade)',
page_info: 'page_num von page_count',
select_ng: 'Achtung: Bitte wählen Sie aus der Liste aus.',
select_ok: 'OK : Richtig ausgewählt.',
not_found: 'nicht gefunden',
ajax_error:
'Bei der Verbindung zum Server ist ein Fehler aufgetreten.',
clear: 'Löschen Sie den Inhalt',
select_all: 'Wähle diese Seite',
unselect_all: 'Diese Seite entfernen',
clear_all: 'Alles löschen',
max_selected:
'Sie können nur bis zu max_selected_limit Elemente auswählen'
}
break
// English
case 'en':
message = {
add_btn: 'Add button',
add_title: 'add a box',
del_btn: 'Del button',
del_title: 'delete a box',
next: 'Next',
next_title: 'Next' + p.pageSize + ' (Right key)',
prev: 'Prev',
prev_title: 'Prev' + p.pageSize + ' (Left key)',
first_title: 'First (Shift + Left key)',
last_title: 'Last (Shift + Right key)',
get_all_btn: 'Get All (Down key)',
get_all_alt: '(button)',
close_btn: 'Close (Tab key)',
close_alt: '(button)',
loading: 'loading...',
loading_alt: '(loading)',
page_info: 'Page page_num of page_count',
select_ng: 'Attention : Please choose from among the list.',
select_ok: 'OK : Correctly selected.',
not_found: 'not found',
ajax_error: 'An error occurred while connecting to server.',
clear: 'Clear content',
select_all: 'Select current page',
unselect_all: 'Clear current page',
clear_all: 'Clear all selected',
max_selected: 'You can only select up to max_selected_limit items'
}
break
// Spanish
case 'es':
message = {
add_btn: 'Agregar boton',
add_title: 'Agregar una opcion',
del_btn: 'Borrar boton',
del_title: 'Borrar una opcion',
next: 'Siguiente',
next_title: 'Proximas ' + p.pageSize + ' (tecla derecha)',
prev: 'Anterior',
prev_title: 'Anteriores ' + p.pageSize + ' (tecla izquierda)',
first_title: 'Primera (Shift + Left)',
last_title: 'Ultima (Shift + Right)',
get_all_btn: 'Ver todos (tecla abajo)',
get_all_alt: '(boton)',
close_btn: 'Cerrar (tecla TAB)',
close_alt: '(boton)',
loading: 'Cargando...',
loading_alt: '(Cargando)',
page_info: 'page_num de page_count',
select_ng: 'Atencion: Elija una opcion de la lista.',
select_ok: 'OK: Correctamente seleccionado.',
not_found: 'no encuentre',
ajax_error: 'Un error ocurrió mientras conectando al servidor.',
clear: 'Borrar el contenido',
select_all: 'Elija esta página',
unselect_all: 'Borrar esta página',
clear_all: 'Borrar todo marcado',
max_selected:
'Solo puedes seleccionar hasta max_selected_limit elementos'
}
break
// Brazilian Portuguese
case 'pt-br':
message = {
add_btn: 'Adicionar botão',
add_title: 'Adicionar uma caixa',
del_btn: 'Apagar botão',
del_title: 'Apagar uma caixa',
next: 'Próxima',
next_title: 'Próxima ' + p.pageSize + ' (tecla direita)',
prev: 'Anterior',
prev_title: 'Anterior ' + p.pageSize + ' (tecla esquerda)',
first_title: 'Primeira (Shift + Left)',
last_title: 'Última (Shift + Right)',
get_all_btn: 'Ver todos (Seta para baixo)',
get_all_alt: '(botão)',
close_btn: 'Fechar (tecla TAB)',
close_alt: '(botão)',
loading: 'Carregando...',
loading_alt: '(Carregando)',
page_info: 'page_num de page_count',
select_ng: 'Atenção: Escolha uma opção da lista.',
select_ok: 'OK: Selecionado Corretamente.',
not_found: 'não encontrado',
ajax_error: 'Um erro aconteceu enquanto conectando a servidor.',
clear: 'Limpe o conteúdo',
select_all: 'Selecione a página atual',
unselect_all: 'Remova a página atual',
clear_all: 'Limpar tudo',
max_selected: 'Você só pode selecionar até max_selected_limit itens'
}
break
// Japanese
case 'ja':
message = {
add_btn: '追加ボタン',
add_title: '入力ボックスを追加します',
del_btn: '削除ボタン',
del_title: '入力ボックスを削除します',
next: '次へ',
next_title: '次の' + p.pageSize + '件 (右キー)',
prev: '前へ',
prev_title: '前の' + p.pageSize + '件 (左キー)',
first_title: '最初のページへ (Shift + 左キー)',
last_title: '最後のページへ (Shift + 右キー)',
get_all_btn: '全件取得 (下キー)',
get_all_alt: '画像:ボタン',
close_btn: '閉じる (Tabキー)',
close_alt: '画像:ボタン',
loading: '読み込み中...',
loading_alt: '画像:読み込み中...',
page_info: 'page_num 件 (全 page_count 件)',
select_ng: '注意 : リストの中から選択してください',
select_ok: 'OK : 正しく選択されました。',
not_found: '(0 件)',
ajax_error: 'サーバとの通信でエラーが発生しました。',
clear: 'コンテンツをクリアする',
select_all: '当ページを選びます',
unselect_all: '移して当ページを割ります',
clear_all: '選択した項目をクリアする',
max_selected:
'最多で max_selected_limit のプロジェクトを選ぶことしかできません'
}
break
// 中文
case 'cn':
default:
message = {
add_btn: '添加按钮',
add_title: '添加区域',
del_btn: '删除按钮',
del_title: '删除区域',
next: '下一页',
next_title: '下' + p.pageSize + ' (→)',
prev: '上一页',
prev_title: '上' + p.pageSize + ' (←)',
first_title: '首页 (Shift + ←)',
last_title: '尾页 (Shift + →)',
get_all_btn: '获得全部 (↓)',
get_all_alt: '(按钮)',
close_btn: '关闭 (Tab键)',
close_alt: '(按钮)',
loading: '读取中...',
loading_alt: '(读取中)',
page_info: '第 page_num 页(共page_count页)',
select_ng: '请注意:请从列表中选择.',
select_ok: 'OK : 已经选择.',
not_found: '无查询结果',
ajax_error: '连接到服务器时发生错误!',
clear: '清除内容',
select_all: '选择当前页项目',
unselect_all: '取消选择当前页项目',
clear_all: '清除全部已选择项目',
max_selected: '最多只能选择 max_selected_limit 个项目'
}
break
}
this.message = message
}
/**
* Css classname defined
*/
SelectPage.prototype.setCssClass = function () {
var css_class = {
container: 'sp_container',
container_open: 'sp_container_open',
re_area: 'sp_result_area',
result_open: 'sp_result_area_open',
control_box: 'sp_control_box',
//multiple select mode
element_box: 'sp_element_box',
navi: 'sp_navi',
//result list
results: 'sp_results',
re_off: 'sp_results_off',
select: 'sp_over',
select_ok: 'sp_select_ok',
select_ng: 'sp_select_ng',
selected: 'sp_selected',
input_off: 'sp_input_off',
message_box: 'sp_message_box',
disabled: 'sp_disabled',
button: 'sp_button',
caret_open: 'sp_caret_open',
btn_on: 'sp_btn_on',
btn_out: 'sp_btn_out',
input: 'sp_input',
clear_btn: 'sp_clear_btn',
align_right: 'sp_align_right'
}
this.css_class = css_class
}
/**
* Plugin inner properties
*/
SelectPage.prototype.setProp = function () {
this.prop = {
//input disabled status
disabled: false,
current_page: 1,
//total page
max_page: 1,
//ajax data loading status
is_loading: false,
xhr: false,
key_paging: false,
key_select: false,
//last selected item value
prev_value: '',
//last selected item text
selected_text: '',
last_input_time: undefined,
init_set: false
}
this.template = {
tag: {
content:
'<li class="selected_tag" itemvalue="#item_value#">#item_text#<span class="tag_close"><i class="sp-iconfont if-close"></i></span></li>',
textKey: '#item_text#',
valueKey: '#item_value#'
},
page: {
current: 'page_num',
total: 'page_count'
},
msg: {
maxSelectLimit: 'max_selected_limit'
}
}
}
/**
* Get the actual width/height of invisible DOM elements with jQuery.
* Source code come from dreamerslab/jquery.actual
* @param element
* @param method
* @returns {*}
*/
SelectPage.prototype.elementRealSize = function (element, method) {
var defaults = {
absolute: false,
clone: false,
includeMargin: false,
display: 'block'
}
var configs = defaults,
$target = element.eq(0),
fix,
restore,
tmp = [],
style = '',
$hidden
fix = function () {
// get all hidden parents
$hidden = $target.parents().addBack().filter(':hidden')
style +=
'visibility: hidden !important; display: ' +
configs.display +
' !important; '
if (configs.absolute === true) style += 'position: absolute !important;'
// save the origin style props
// set the hidden el css to be got the actual value later
$hidden.each(function () {
// Save original style. If no style was set, attr() returns undefined
var $this = $(this), thisStyle = $this.attr('style')
tmp.push(thisStyle)
// Retain as much of the original style as possible, if there is one
$this.attr('style', thisStyle ? thisStyle + ';' + style : style)
})
}
restore = function () {
// restore origin style values
$hidden.each(function (i) {
var $this = $(this),
_tmp = tmp[i]
if (_tmp === undefined) $this.removeAttr('style')
else $this.attr('style', _tmp)
})
}
fix()
// get the actual value with user specific methed
// it can be 'width', 'height', 'outerWidth', 'innerWidth'... etc
// configs.includeMargin only works for 'outerWidth' and 'outerHeight'
var actual = /(outer)/.test(method)
? $target[method](configs.includeMargin)
: $target[method]()
restore()
// IMPORTANT, this plugin only return the value of the first element
return actual
}
/**
* Dom building
* @param {Object} combo_input - original input element
*/
SelectPage.prototype.setElem = function (combo_input) {
// 1. build Dom object
var elem = {},
p = this.option,
css = this.css_class,
msg = this.message,
input = $(combo_input)
var orgWidth = input.outerWidth()
// fix input width in hidden situation
if (orgWidth <= 0) orgWidth = this.elementRealSize(input, 'outerWidth')
if (orgWidth < 150) orgWidth = 150
elem.combo_input = input
.attr({ autocomplete: 'off' })
.addClass(css.input)
.wrap('<div>')
if (p.selectOnly) elem.combo_input.prop('readonly', true)
elem.container = elem.combo_input.parent().addClass(css.container)
if (elem.combo_input.prop('disabled')) {
if (p.multiple) elem.container.addClass(css.disabled)
else elem.combo_input.addClass(css.input_off)
}
// set outer box width
elem.container.width(orgWidth)
elem.button = $('<div>').addClass(css.button)
// drop down button
elem.dropdown = $('<span class="sp_caret"></span>')
// clear button 'X' in single mode
elem.clear_btn = $('<div>')
.html($('<i>').addClass('sp-iconfont if-close'))
.addClass(css.clear_btn)
.attr('title', msg.clear)
if (!p.dropButton) elem.clear_btn.addClass(css.align_right)
// main box in multiple mode
elem.element_box = $('<ul>').addClass(css.element_box)
if (p.multiple && p.multipleControlbar)
elem.control = $('<div>').addClass(css.control_box)
// result list box
elem.result_area = $('<div>').addClass(css.re_area)
// pagination bar
if (p.pagination)
elem.navi = $('<div>').addClass('sp_pagination').append('<ul>')
elem.results = $('<ul>').addClass(css.results)
var namePrefix = '_text',
input_id = elem.combo_input.attr('id') || elem.combo_input.attr('name'),
input_name = elem.combo_input.attr('name') || 'selectPage',
hidden_name = input_name,
hidden_id = input_id
// switch the id and name attributes of input/hidden element
elem.hidden = $('<input type="hidden" class="sp_hidden" />')
.attr({
name: hidden_name,
id: hidden_id
})
.val('')
elem.combo_input.attr({
name: input_name + namePrefix,
id: input_id + namePrefix
})
// 2. DOM element put
elem.container.append(elem.hidden)
if (p.dropButton) {
elem.container.append(elem.button)
elem.button.append(elem.dropdown)
}
$(document.body).append(elem.result_area)
elem.result_area.append(elem.results)
if (p.pagination) elem.result_area.append(elem.navi)
//Multiple select mode
if (p.multiple) {
if (p.multipleControlbar) {
elem.control.append(
'<button type="button" class="btn btn-default sp_clear_all" ><i class="sp-iconfont if-clear"></i></button>'
)
elem.control.append(
'<button type="button" class="btn btn-default sp_unselect_all" ><i class="sp-iconfont if-unselect-all"></i></button>'
)
elem.control.append(
'<button type="button" class="btn btn-default sp_select_all" ><i class="sp-iconfont if-select-all"></i></button>'
)
elem.control_text = $('<p>')
elem.control.append(elem.control_text)
elem.result_area.prepend(elem.control)
}
elem.container.addClass('sp_container_combo')
elem.combo_input.addClass('sp_combo_input').before(elem.element_box)
var li = $('<li>').addClass('input_box')
li.append(elem.combo_input)
elem.element_box.append(li)
if (elem.combo_input.attr('placeholder'))
elem.combo_input.attr(
'placeholder_bak',
elem.combo_input.attr('placeholder')
)
}
this.elem = elem
}
/**
* Drop down button set to default
*/
SelectPage.prototype.setButtonAttrDefault = function () {
/*
if (this.option.selectOnly) {
if ($(this.elem.combo_input).val() !== '') {
if ($(this.elem.hidden).val() !== '') {
//选择条件
$(this.elem.combo_input).attr('title', this.message.select_ok).removeClass(this.css_class.select_ng).addClass(this.css_class.select_ok);
} else {
//输入方式
$(this.elem.combo_input).attr('title', this.message.select_ng).removeClass(this.css_class.select_ok).addClass(this.css_class.select_ng);
}
} else {
$(this.elem.hidden).val('');
$(this.elem.combo_input).removeAttr('title').removeClass(this.css_class.select_ng);
}
}
*/
//this.elem.button.attr('title', this.message.get_all_btn);
if (this.option.dropButton)
this.elem.button.attr('title', this.message.close_btn)
}
/**
* Set item need selected after init
* set selected item ways:
* <input value="key">
* <input data-init="key">
*/
SelectPage.prototype.setInitRecord = function (refresh) {
var self = this, p = self.option, el = self.elem, key = ''
if ($.type(el.combo_input.data('init')) != 'undefined') {
p.initRecord = String(el.combo_input.data('init'))
}
//data-init and value attribute can be init plugin selected item
//but, if set data-init and value attribute in the same time, plugin will choose data-init attribute first
if (!refresh && !p.initRecord && el.combo_input.val()) {
p.initRecord = el.combo_input.val()
}
el.combo_input.val('')
if (!refresh) {
el.hidden.val(p.initRecord)
}
key = refresh && el.hidden.val() ? el.hidden.val() : p.initRecord
if (key) {
if (typeof p.data === 'object') {
var data = new Array()
var keyarr = key.split(',')
$.each(keyarr, function (index, row) {
for (var i = 0; i < p.data.length; i++) {
if (p.data[i][p.keyField] == row) {
data.push(p.data[i])
break
}
}
})
if (!p.multiple && data.length > 1) data = [data[0]]
self.afterInit(self, data)
} else {
//ajax data source mode to init selected item
$.ajax({
dataType: 'json',
type: 'POST',
url: p.data,
data: {
searchTable: p.dbTable,
searchKey: p.keyField,
searchValue: key
},
success: function (json) {
var d = null
if (p.eAjaxSuccess && $.isFunction(p.eAjaxSuccess))
d = p.eAjaxSuccess(json)
self.afterInit(self, d.list)
},
error: function () {
self.ajaxErrorNotify(self)
}
})
}
}
}
/**
* Selected item set to plugin
* @param {Object} self
* @param {Object} data - selected item data
*/
SelectPage.prototype.afterInit = function (self, data) {
if (!data || ($.isArray(data) && data.length === 0)) return
if (!$.isArray(data)) data = [data]
var p = self.option,
css = self.css_class
var getText = function (row) {
var text = row[p.showField]
if (p.formatItem && $.isFunction(p.formatItem)) {
try {
text = p.formatItem(row)
} catch (e) {}
}
return text
}
if (p.multiple) {
self.prop.init_set = true
self.clearAll(self)
$.each(data, function (i, row) {
var item = { text: getText(row), value: row[p.keyField] }
if (!self.isAlreadySelected(self, item)) self.addNewTag(self, row, item)
})
self.tagValuesSet(self)
self.inputResize(self)
self.prop.init_set = false
} else {
var row = data[0]
self.elem.combo_input.val(getText(row))
self.elem.hidden.val(row[p.keyField])
self.prop.prev_value = getText(row)
self.prop.selected_text = getText(row)
if (p.selectOnly) {
self.elem.combo_input
.attr('title', self.message.select_ok)
.removeClass(css.select_ng)
.addClass(css.select_ok)
}
self.putClearButton()
}
}
/**
* Drop down button event bind
*/
SelectPage.prototype.eDropdownButton = function () {
var self = this
if (self.option.dropButton) {
self.elem.button.mouseup(function (ev) {
ev.stopPropagation()
if (
self.elem.result_area.is(':hidden') &&
!self.elem.combo_input.prop('disabled')
) {
self.elem.combo_input.focus()
} else self.hideResults(self)
})
}
}
/**
* Events bind
*/
SelectPage.prototype.eInput = function () {
var self = this, p = self.option, el = self.elem, msg = self.message
var showList = function () {
self.prop.page_move = false
self.suggest(self)
self.setCssFocusedInput(self)
}
el.combo_input
.keyup(function (e) {
self.processKey(self, e)
})
.keydown(function (e) {
self.processControl(self, e)
})
.focus(function (e) {
// When focus on input, show the result list
if (el.result_area.is(':hidden')) {
e.stopPropagation()
self.prop.first_show = true
showList()
}
})
el.container.on(
'click.SelectPage',
'div.' + self.css_class.clear_btn,
function (e) {
e.stopPropagation()
if (!self.disabled(self)) {
self.clearAll(self, true)
if (p.eClear && $.isFunction(p.eClear)) p.eClear(self)
}
}
)
el.result_area.on('mousedown.SelectPage', function (e) {
e.stopPropagation()
})
if (p.multiple) {
if (p.multipleControlbar) {
// Select all item of current page
el.control
.find('.sp_select_all')
.on('click.SelectPage', function () {
self.selectAllLine(self)
})
.hover(
function () {
el.control_text.html(msg.select_all)
},
function () {
el.control_text.html('')
}
)
// Cancel select all item of current page
el.control
.find('.sp_unselect_all')
.on('click.SelectPage', function () {
self.unSelectAllLine(self)
})
.hover(
function () {
el.control_text.html(msg.unselect_all)
},
function () {
el.control_text.html('')
}
)
// Clear all selected item
el.control
.find('.sp_clear_all')
.on('click.SelectPage', function () {
self.clearAll(self, true)
})
.hover(
function () {
el.control_text.html(msg.clear_all)
},
function () {
el.control_text.html('')
}
)
}
el.element_box.on('click.SelectPage', function (e) {
var srcEl = e.target || e.srcElement
if ($(srcEl).is('ul')) el.combo_input.focus()
})
// Tag close