selectpage.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  1. /**
  2. * @summary SelectPage
  3. * @desc Simple and powerful selection plugin
  4. * @file selectpage.js
  5. * @version 2.20
  6. * @author TerryZeng
  7. * @contact https://terryz.github.io/
  8. * @license MIT License
  9. *
  10. */
  11. ;(function ($) {
  12. "use strict";
  13. /**
  14. * Default options
  15. */
  16. var defaults = {
  17. /**
  18. * Data source
  19. * @type {string|Object}
  20. *
  21. * string:server side request url address
  22. * Object:JSON array,format:[{a:1,b:2,c:3},{...}]
  23. */
  24. data: undefined,
  25. /**
  26. * Language ('cn', 'en')
  27. * @type string
  28. * @default 'cn'
  29. */
  30. lang: 'cn',
  31. /**
  32. * Multiple select mode(tags)
  33. * @type boolean
  34. * @default false
  35. */
  36. multiple: false,
  37. /**
  38. * pagination or not
  39. * @type boolean
  40. * @default true
  41. */
  42. pagination: true,
  43. /**
  44. * Show up menu button
  45. * @type boolean
  46. * @default true
  47. */
  48. dropButton: true,
  49. /**
  50. * Result list visible size in pagination bar close
  51. * @type number
  52. * @default 10
  53. */
  54. listSize: 10,
  55. /**
  56. * Show control bar in multiple select mode
  57. * @type boolean
  58. * @default true
  59. */
  60. multipleControlbar: true,
  61. /**
  62. * Max selected item limited in multiple select mode
  63. * @type number
  64. * @default 0(unlimited)
  65. */
  66. maxSelectLimit: 0,
  67. /**
  68. * Select result item to close list, work on multiple select mode
  69. * @type boolean
  70. * @default false
  71. */
  72. selectToCloseList: false,
  73. /**
  74. * Init selected item key, the result will match to option.keyField option
  75. * @type string
  76. */
  77. initRecord: undefined,
  78. /**
  79. * The table parameter in server side mode
  80. * @type string
  81. */
  82. dbTable: 'tbl',
  83. /**
  84. * The value field, the value will fill to hidden element
  85. * @type string
  86. * @default 'id'
  87. */
  88. keyField: 'id',
  89. /**
  90. * The show text field, the text will show to input element or tags(multiple mode)
  91. * @type string
  92. * @default 'name'
  93. */
  94. showField: 'name',
  95. /**
  96. * Actually used to search field
  97. * @type string
  98. */
  99. searchField: undefined,
  100. /**
  101. * escape content
  102. */
  103. escape: true,
  104. /**
  105. * Search type ('AND' or 'OR')
  106. * @type string
  107. * @default 'AND'
  108. */
  109. andOr: 'OR',
  110. /**
  111. * Used to separate search content
  112. * @see SelectPage.prototype.suggest()
  113. */
  114. separator: ',',
  115. /**
  116. * Result sort type
  117. * @type array|boolean - if not set, will default used showField field
  118. * @example
  119. * orderBy : ['id desc']
  120. */
  121. orderBy: undefined,
  122. /**
  123. * Page size
  124. * @type number
  125. * @default 10
  126. */
  127. pageSize: 10,
  128. /**
  129. * Server side request parameters
  130. * @type function
  131. * @return object
  132. * @example params : function(){return {'name':'aa','sex':1};}
  133. */
  134. params: undefined,
  135. /**
  136. * Custom result list item show text
  137. * @type function
  138. * @param data {object} row data
  139. * @return string
  140. */
  141. formatItem: undefined,
  142. /**
  143. * Have some highlight item and lost focus, auto select the highlight item
  144. * @type boolean
  145. * @default false
  146. */
  147. autoFillResult: false,
  148. /**
  149. * Auto select first item in show up result list or search result
  150. * depend on `autoFillResult` option set to true
  151. * @type boolean
  152. * @default false
  153. */
  154. autoSelectFirst: false,
  155. /**
  156. * Whether clear input element text when enter some keywords to search and no result return
  157. * @type boolean
  158. * @default true
  159. */
  160. noResultClean: true,
  161. /**
  162. * Select only mode
  163. * @type boolean
  164. */
  165. selectOnly: false,
  166. /**
  167. * Input to search delay time, work on ajax data source
  168. * @type number
  169. * @default 0.5
  170. */
  171. inputDelay: 0.5,
  172. /**
  173. * -----------------------------------------Callback--------------------------------------------
  174. */
  175. /**
  176. * Result list item selected callback
  177. * @type function
  178. * @param object - selected item json data
  179. * @param self - plugin object
  180. */
  181. eSelect: undefined,
  182. /**
  183. * Before result list show up callback, you can do anything prepared
  184. * @param self - plugin object
  185. */
  186. eOpen: undefined,
  187. /**
  188. * Server side return data convert callback
  189. * @type function
  190. * @param data {object} server side return data
  191. * @param self {object} plugin object
  192. * @return {object} return data format:
  193. * @example
  194. * {
  195. * list : [{name:'aa',sex:1},{name:'bb',sex:1}...],
  196. * totalRow : 100
  197. * }
  198. */
  199. eAjaxSuccess: undefined,
  200. /**
  201. * Close selected item tag callback (multiple mode)
  202. * @type function
  203. * @param removeCount {number} remove item count
  204. * @param self {object} plugin object
  205. */
  206. eTagRemove: undefined,
  207. /**
  208. * Clear selected item callback(single select mode)
  209. * @type function
  210. * @param self {object} plugin object
  211. */
  212. eClear: undefined
  213. };
  214. /**
  215. * SelectPage class definition
  216. * @constructor
  217. * @param {Object} input - input element
  218. * @param {Object} option
  219. */
  220. var SelectPage = function (input, option) {
  221. //特殊字段处理
  222. $.each({data: 'source', keyField: 'primaryKey', showField: 'field', pageSize: 'perPage'}, function (i, j) {
  223. if (typeof option[j] !== 'undefined') {
  224. option[i] = option[j];
  225. delete option[j];
  226. }
  227. });
  228. this.setOption(option);
  229. this.setLanguage();
  230. this.setCssClass();
  231. this.setProp();
  232. this.setElem(input);
  233. this.setButtonAttrDefault();
  234. this.setInitRecord();
  235. this.eDropdownButton();
  236. this.eInput();
  237. this.eWhole();
  238. };
  239. /**
  240. * Plugin version number
  241. */
  242. SelectPage.version = '2.19';
  243. /**
  244. * Plugin object cache key
  245. */
  246. SelectPage.dataKey = 'selectPageObject';
  247. /**
  248. * Options set
  249. * @param {Object} option
  250. */
  251. SelectPage.prototype.setOption = function (option) {
  252. //use showField to default
  253. option.searchField = option.searchField || option.showField;
  254. option.andOr = option.andOr.toUpperCase();
  255. if (option.andOr !== 'AND' && option.andOr !== 'OR') option.andOr = 'AND';
  256. //support multiple field set
  257. var arr = ['searchField'];
  258. for (var i = 0; i < arr.length; i++) {
  259. option[arr[i]] = this.strToArray(option[arr[i]]);
  260. }
  261. //set default order field
  262. option.orderBy = option.orderBy || option.showField;
  263. //set multiple order field
  264. //example: [ ['id', 'ASC'], ['name', 'DESC'] ]
  265. if (option.orderBy !== false) option.orderBy = this.setOrderbyOption(option.orderBy, option.showField);
  266. //close auto fill result and auto select first in multiple mode and select item not close list
  267. if (option.multiple && !option.selectToCloseList) {
  268. option.autoFillResult = false;
  269. option.autoSelectFirst = false;
  270. }
  271. //show all item when pagination bar close, limited 200
  272. if (!option.pagination) option.pageSize = 200;
  273. if ($.type(option.listSize) !== 'number' || option.listSize < 0) option.listSize = 10;
  274. if (typeof option.formatItem === 'string') {
  275. var _formatItem = option.formatItem;
  276. option.formatItem = function (row) {
  277. if (typeof Template === 'function' && _formatItem.match(/\#([a-zA-Z0-9_\-]+)$/)) {
  278. return Template(_formatItem.substring(1), row);
  279. } else {
  280. return _formatItem.replace(/\{(.*?)\}/gi, function (matched) {
  281. matched = matched.substring(1, matched.length - 1);
  282. return typeof row[matched] !== 'undefined' ? row[matched] : '';
  283. });
  284. }
  285. };
  286. }
  287. this.option = option;
  288. };
  289. /**
  290. * escape html
  291. * @param text
  292. * @returns {*|string}
  293. */
  294. SelectPage.prototype.escapeHTML = function (text) {
  295. if (typeof text === 'string') {
  296. return text
  297. .replace(/&/g, '&amp;')
  298. .replace(/</g, '&lt;')
  299. .replace(/>/g, '&gt;')
  300. .replace(/"/g, '&quot;')
  301. .replace(/'/g, '&#039;')
  302. .replace(/`/g, '&#x60;');
  303. }
  304. return text;
  305. };
  306. /**
  307. * String convert to array
  308. * @param str {string}
  309. * @return {Array}
  310. */
  311. SelectPage.prototype.strToArray = function (str) {
  312. return str ? str.replace(/[\s ]+/g, '').split(',') : '';
  313. };
  314. /**
  315. * Set order field
  316. * @param {Array} arg_order
  317. * @param {string} arg_field - default sort field
  318. * @return {Array}
  319. */
  320. SelectPage.prototype.setOrderbyOption = function (arg_order, arg_field) {
  321. var arr = [], orders = [];
  322. if (typeof arg_order === 'object') {
  323. for (var i = 0; i < arg_order.length; i++) {
  324. orders = $.trim(arg_order[i]).split(' ');
  325. if (orders.length)
  326. arr.push((orders.length === 2) ? orders.concat() : [orders[0], 'ASC']);
  327. }
  328. } else {
  329. orders = $.trim(arg_order).split(' ');
  330. arr[0] = (orders.length === 2) ? orders.concat() : (orders[0].toUpperCase().match(/^(ASC|DESC)$/i)) ? [arg_field, orders[0].toUpperCase()] : [orders[0], 'ASC'];
  331. }
  332. return arr;
  333. };
  334. /**
  335. * i18n
  336. */
  337. SelectPage.prototype.setLanguage = function () {
  338. var message, p = this.option;
  339. switch (p.lang) {
  340. // English
  341. case 'en':
  342. message = {
  343. add_btn: 'Add button',
  344. add_title: 'add a box',
  345. del_btn: 'Del button',
  346. del_title: 'delete a box',
  347. next: 'Next',
  348. next_title: 'Next' + p.pageSize + ' (Right key)',
  349. prev: 'Prev',
  350. prev_title: 'Prev' + p.pageSize + ' (Left key)',
  351. first_title: 'First (Shift + Left key)',
  352. last_title: 'Last (Shift + Right key)',
  353. get_all_btn: 'Get All (Down key)',
  354. get_all_alt: '(button)',
  355. close_btn: 'Close (Tab key)',
  356. close_alt: '(button)',
  357. loading: 'loading...',
  358. loading_alt: '(loading)',
  359. page_info: 'page_num of page_count',
  360. select_ng: 'Attention : Please choose from among the list.',
  361. select_ok: 'OK : Correctly selected.',
  362. not_found: 'not found',
  363. ajax_error: 'An error occurred while loading data.',
  364. clear: 'Clear content',
  365. select_all: 'Select current page',
  366. unselect_all: 'Clear current page',
  367. clear_all: 'Clear all selected',
  368. max_selected: 'You can only select up to max_selected_limit items'
  369. };
  370. break;
  371. // 中文
  372. case 'cn':
  373. default:
  374. message = {
  375. add_btn: '添加按钮',
  376. add_title: '添加区域',
  377. del_btn: '删除按钮',
  378. del_title: '删除区域',
  379. next: '下一页',
  380. next_title: '下' + p.pageSize + ' (→)',
  381. prev: '上一页',
  382. prev_title: '上' + p.pageSize + ' (←)',
  383. first_title: '首页 (Shift + ←)',
  384. last_title: '尾页 (Shift + →)',
  385. get_all_btn: '获得全部 (↓)',
  386. get_all_alt: '(按钮)',
  387. close_btn: '关闭 (Tab键)',
  388. close_alt: '(按钮)',
  389. loading: '读取中...',
  390. loading_alt: '(读取中)',
  391. page_info: '第 page_num 页(共page_count页)',
  392. select_ng: '请注意:请从列表中选择.',
  393. select_ok: 'OK : 已经选择.',
  394. not_found: '无查询结果',
  395. ajax_error: '加载数据时发生了错误!',
  396. clear: '清除内容',
  397. select_all: '选择当前页项目',
  398. unselect_all: '取消选择当前页项目',
  399. clear_all: '清除全部已选择项目',
  400. max_selected: '最多只能选择 max_selected_limit 个项目'
  401. };
  402. break;
  403. }
  404. this.message = message;
  405. };
  406. /**
  407. * Css classname defined
  408. */
  409. SelectPage.prototype.setCssClass = function () {
  410. var css_class = {
  411. container: 'sp_container',
  412. container_open: 'sp_container_open',
  413. re_area: 'sp_result_area',
  414. result_open: 'sp_result_area_open',
  415. control_box: 'sp_control_box',
  416. //multiple select mode
  417. element_box: 'sp_element_box',
  418. navi: 'sp_navi',
  419. //result list
  420. results: 'sp_results',
  421. re_off: 'sp_results_off',
  422. select: 'sp_over',
  423. select_ok: 'sp_select_ok',
  424. select_ng: 'sp_select_ng',
  425. selected: 'sp_selected',
  426. input_off: 'sp_input_off',
  427. message_box: 'sp_message_box',
  428. disabled: 'sp_disabled',
  429. button: 'sp_button',
  430. caret_open: 'sp_caret_open',
  431. btn_on: 'sp_btn_on',
  432. btn_out: 'sp_btn_out',
  433. input: 'sp_input',
  434. clear_btn: 'sp_clear_btn',
  435. align_right: 'sp_align_right'
  436. };
  437. this.css_class = css_class;
  438. };
  439. /**
  440. * Plugin inner properties
  441. */
  442. SelectPage.prototype.setProp = function () {
  443. this.prop = {
  444. //input disabled status
  445. disabled: false,
  446. current_page: 1,
  447. //total page
  448. max_page: 1,
  449. //ajax data loading status
  450. is_loading: false,
  451. xhr: false,
  452. key_paging: false,
  453. key_select: false,
  454. //last selected item value
  455. prev_value: '',
  456. //last selected item text
  457. selected_text: '',
  458. last_input_time: undefined,
  459. init_set: false
  460. };
  461. this.template = {
  462. tag: {
  463. content: '<li class="selected_tag" itemvalue="#item_value#">#item_text#<span class="tag_close"><i class="spfont sp-close"></i></span></li>',
  464. textKey: '#item_text#',
  465. valueKey: '#item_value#'
  466. },
  467. page: {
  468. current: 'page_num',
  469. total: 'page_count'
  470. },
  471. msg: {
  472. maxSelectLimit: 'max_selected_limit'
  473. }
  474. };
  475. };
  476. /**
  477. * Get the actual width/height of invisible DOM elements with jQuery.
  478. * Source code come from dreamerslab/jquery.actual
  479. * @param element
  480. * @param method
  481. * @returns {*}
  482. */
  483. SelectPage.prototype.elementRealSize = function (element, method) {
  484. var defaults = {
  485. absolute: false,
  486. clone: false,
  487. includeMargin: false,
  488. display: 'block'
  489. };
  490. var configs = defaults, $target = element.eq(0), fix, restore, tmp = [], style = '', $hidden;
  491. fix = function () {
  492. // get all hidden parents
  493. $hidden = $target.parents().addBack().filter(':hidden');
  494. style += 'visibility: hidden !important; display: ' + configs.display + ' !important; ';
  495. if (configs.absolute === true) style += 'position: absolute !important;';
  496. // save the origin style props
  497. // set the hidden el css to be got the actual value later
  498. $hidden.each(function () {
  499. // Save original style. If no style was set, attr() returns undefined
  500. var $this = $(this), thisStyle = $this.attr('style');
  501. tmp.push(thisStyle);
  502. // Retain as much of the original style as possible, if there is one
  503. $this.attr('style', thisStyle ? thisStyle + ';' + style : style);
  504. });
  505. };
  506. restore = function () {
  507. // restore origin style values
  508. $hidden.each(function (i) {
  509. var $this = $(this), _tmp = tmp[i];
  510. if (_tmp === undefined) $this.removeAttr('style');
  511. else $this.attr('style', _tmp);
  512. });
  513. };
  514. fix();
  515. // get the actual value with user specific methed
  516. // it can be 'width', 'height', 'outerWidth', 'innerWidth'... etc
  517. // configs.includeMargin only works for 'outerWidth' and 'outerHeight'
  518. var actual = /(outer)/.test(method) ?
  519. $target[method](configs.includeMargin) :
  520. $target[method]();
  521. restore();
  522. // IMPORTANT, this plugin only return the value of the first element
  523. return actual;
  524. };
  525. /**
  526. * Dom building
  527. * @param {Object} combo_input - original input element
  528. */
  529. SelectPage.prototype.setElem = function (combo_input) {
  530. // 1. build Dom object
  531. var elem = {}, p = this.option, css = this.css_class, msg = this.message, input = $(combo_input);
  532. var cssWidth = input.css("width");
  533. var orgWidth = input.outerWidth();
  534. if (cssWidth.indexOf("%") > -1 || input.parent().length > 0 && input.parent().width() == orgWidth) {
  535. orgWidth = "100%";
  536. } else {
  537. // fix input width in hidden situation
  538. if (orgWidth <= 0) orgWidth = this.elementRealSize(input, 'outerWidth');
  539. if (orgWidth < 150) orgWidth = 150;
  540. }
  541. elem.combo_input = input.attr({'autocomplete': 'off'}).addClass(css.input).wrap('<div>');
  542. if (p.selectOnly) elem.combo_input.prop('readonly', true);
  543. elem.container = elem.combo_input.parent().addClass(css.container);
  544. if (elem.combo_input.prop('disabled')) {
  545. if (p.multiple) elem.container.addClass(css.disabled);
  546. else elem.combo_input.addClass(css.input_off);
  547. }
  548. // set outer box width
  549. elem.container.width(orgWidth);
  550. elem.button = $('<div>').addClass(css.button);
  551. //drop down button
  552. elem.dropdown = $('<span class="sp_caret"></span>');
  553. //clear button 'X' in single mode
  554. elem.clear_btn = $('<div>').html($('<i>').addClass('spfont sp-close')).addClass(css.clear_btn).attr('title', msg.clear);
  555. if (!p.dropButton) elem.clear_btn.addClass(css.align_right);
  556. //main box in multiple mode
  557. elem.element_box = $('<ul>').addClass(css.element_box);
  558. if (p.multiple && p.multipleControlbar)
  559. elem.control = $('<div>').addClass(css.control_box);
  560. //result list box
  561. elem.result_area = $('<div>').addClass(css.re_area);
  562. //pagination bar
  563. if (p.pagination) elem.navi = $('<div>').addClass('sp_pagination').append('<ul>');
  564. elem.results = $('<ul>').addClass(css.results);
  565. var namePrefix = '_text',
  566. input_id = elem.combo_input.attr('id') || elem.combo_input.attr('name'),
  567. input_name = elem.combo_input.attr('name') || 'selectPage',
  568. hidden_name = input_name,
  569. hidden_id = input_id;
  570. //switch the id and name attributes of input/hidden element
  571. elem.hidden = $('<input type="hidden" class="sp_hidden" />').attr({
  572. name: hidden_name,
  573. id: hidden_id
  574. }).val('');
  575. elem.combo_input.attr({
  576. name: typeof input.data('name') !== 'undefined' ? input.data('name') : input_name + namePrefix,
  577. id: input_id + namePrefix
  578. });
  579. elem.hidden.attr("data-rule", elem.combo_input.data("rule") || '');
  580. elem.combo_input.attr("novalidate", "novalidate");
  581. // 2. DOM element put
  582. elem.container.append(elem.hidden);
  583. if (p.dropButton) {
  584. elem.container.append(elem.button)
  585. elem.button.append(elem.dropdown);
  586. }
  587. $(document.body).append(elem.result_area);
  588. elem.result_area.append(elem.results);
  589. if (p.pagination) elem.result_area.append(elem.navi);
  590. //Multiple select mode
  591. if (p.multiple) {
  592. if (p.multipleControlbar) {
  593. elem.control.append('<button type="button" class="btn btn-default sp_clear_all" ><i class="spfont sp-clear"></i></button>');
  594. elem.control.append('<button type="button" class="btn btn-default sp_unselect_all" ><i class="spfont sp-unselect-all"></i></button>');
  595. elem.control.append('<button type="button" class="btn btn-default sp_select_all" ><i class="spfont sp-select-all"></i></button>');
  596. elem.control_text = $('<p>');
  597. elem.control.append(elem.control_text);
  598. elem.result_area.prepend(elem.control);
  599. }
  600. elem.container.addClass('sp_container_combo');
  601. elem.combo_input.addClass('sp_combo_input').before(elem.element_box);
  602. var li = $('<li>').addClass('input_box');
  603. li.append(elem.combo_input);
  604. elem.element_box.append(li);
  605. if (elem.combo_input.attr('placeholder')) elem.combo_input.attr('placeholder_bak', elem.combo_input.attr('placeholder'));
  606. }
  607. this.elem = elem;
  608. };
  609. /**
  610. * Drop down button set to default
  611. */
  612. SelectPage.prototype.setButtonAttrDefault = function () {
  613. /*
  614. if (this.option.selectOnly) {
  615. if ($(this.elem.combo_input).val() !== '') {
  616. if ($(this.elem.hidden).val() !== '') {
  617. //选择条件
  618. $(this.elem.combo_input).attr('title', this.message.select_ok).removeClass(this.css_class.select_ng).addClass(this.css_class.select_ok);
  619. } else {
  620. //输入方式
  621. $(this.elem.combo_input).attr('title', this.message.select_ng).removeClass(this.css_class.select_ok).addClass(this.css_class.select_ng);
  622. }
  623. } else {
  624. $(this.elem.hidden).val('');
  625. $(this.elem.combo_input).removeAttr('title').removeClass(this.css_class.select_ng);
  626. }
  627. }
  628. */
  629. //this.elem.button.attr('title', this.message.get_all_btn);
  630. if (this.option.dropButton)
  631. this.elem.button.attr('title', this.message.close_btn);
  632. };
  633. /**
  634. * Set item need selected after init
  635. * set selected item ways:
  636. * <input value="key">
  637. * <input data-init="key">
  638. */
  639. SelectPage.prototype.setInitRecord = function (refresh) {
  640. var self = this, p = self.option, el = self.elem, key = '';
  641. if ($.type(el.combo_input.data('init')) != 'undefined')
  642. p.initRecord = String(el.combo_input.data('init'));
  643. //data-init and value attribute can be init plugin selected item
  644. //but, if set data-init and value attribute in the same time, plugin will choose data-init attribute first
  645. if (!refresh && !p.initRecord && el.combo_input.val())
  646. p.initRecord = el.combo_input.val();
  647. el.combo_input.val('');
  648. if (!refresh) el.hidden.val(p.initRecord);
  649. key = refresh && el.hidden.val() ? el.hidden.val() : p.initRecord;
  650. if (key) {
  651. if (typeof p.data === 'object') {
  652. var data = new Array();
  653. var keyarr = key.split(',');
  654. $.each(keyarr, function (index, row) {
  655. for (var i = 0; i < p.data.length; i++) {
  656. if (p.data[i][p.keyField] == row) {
  657. data.push(p.data[i]);
  658. break;
  659. }
  660. }
  661. });
  662. if (!p.multiple && data.length > 1) data = [data[0]];
  663. self.afterInit(self, data);
  664. } else {//ajax data source mode to init selected item
  665. var _paramsFunc = p.params, _params = {}, searchKey = p.searchField;
  666. var _orgParams = {
  667. searchTable: p.dbTable,
  668. searchKey: p.keyField,
  669. searchValue: key,
  670. orderBy: p.orderBy,
  671. showField: p.showField,
  672. keyField: p.keyField,
  673. keyValue: key,
  674. searchField: p.searchField
  675. };
  676. if (_paramsFunc) {
  677. var result = $.isFunction(_paramsFunc) ? _paramsFunc(self) : _paramsFunc;
  678. if (result && $.isPlainObject(result)) {
  679. _params = $.extend({}, _orgParams, result);
  680. } else {
  681. _params = _orgParams;
  682. }
  683. } else {
  684. _params = _orgParams;
  685. }
  686. $.ajax({
  687. dataType: 'json',
  688. type: 'POST',
  689. url: p.data,
  690. data: _params,
  691. success: function (json) {
  692. var d = null;
  693. if (p.eAjaxSuccess && $.isFunction(p.eAjaxSuccess))
  694. d = p.eAjaxSuccess(json);
  695. self.afterInit(self, d.list);
  696. },
  697. error: function (jqXHR, textStatus, errorThrown) {
  698. self.ajaxErrorNotify(self, errorThrown);
  699. }
  700. });
  701. }
  702. }
  703. };
  704. /**
  705. * Selected item set to plugin
  706. * @param {Object} self
  707. * @param {Object} data - selected item data
  708. */
  709. SelectPage.prototype.afterInit = function (self, data) {
  710. if (!data || ($.isArray(data) && data.length === 0)) return;
  711. if (!$.isArray(data)) data = [data];
  712. var p = self.option, css = self.css_class;
  713. self.data = data;
  714. if (p.multiple) {
  715. self.prop.init_set = true;
  716. self.clearAll(self);
  717. $.each(data, function (i, row) {
  718. var value = p.escape ? self.escapeHTML(row[p.keyField]) : row[p.keyField];
  719. var text = p.escape ? self.escapeHTML(row[p.showField]) : row[p.showField];
  720. var item = {text: text, value: value};
  721. if (!self.isAlreadySelected(self, item)) self.addNewTag(self, row, item);
  722. });
  723. self.tagValuesSet(self);
  724. self.inputResize(self);
  725. self.elem.hidden.blur();
  726. self.prop.init_set = false;
  727. } else {
  728. var row = data[0];
  729. var value = p.escape ? self.escapeHTML(row[p.keyField]) : row[p.keyField];
  730. var text = p.escape ? self.escapeHTML(row[p.showField]) : row[p.showField];
  731. self.elem.combo_input.val(text);
  732. self.elem.hidden.val(value);
  733. self.prop.prev_value = text;
  734. self.prop.selected_text = text;
  735. if (p.selectOnly) {
  736. self.elem.combo_input.attr('title', self.message.select_ok).removeClass(css.select_ng).addClass(css.select_ok);
  737. }
  738. self.putClearButton();
  739. }
  740. };
  741. /**
  742. * Drop down button event bind
  743. */
  744. SelectPage.prototype.eDropdownButton = function () {
  745. var self = this;
  746. if (self.option.dropButton) {
  747. self.elem.button.mouseup(function (ev) {
  748. ev.stopPropagation();
  749. if (self.elem.result_area.is(':hidden') && !self.elem.combo_input.prop('disabled')) {
  750. self.elem.combo_input.focus();
  751. } else self.hideResults(self);
  752. });
  753. }
  754. };
  755. /**
  756. * Events bind
  757. */
  758. SelectPage.prototype.eInput = function () {
  759. var self = this, p = self.option, el = self.elem, msg = self.message;
  760. var showList = function () {
  761. self.prop.page_move = false;
  762. self.suggest(self);
  763. self.setCssFocusedInput(self);
  764. };
  765. el.combo_input.keyup(function (e) {
  766. self.processKey(self, e);
  767. }).keydown(function (e) {
  768. self.processControl(self, e);
  769. }).focus(function (e) {
  770. //When focus on input, show the result list
  771. if (el.result_area.is(':hidden')) {
  772. e.stopPropagation();
  773. self.prop.first_show = true;
  774. showList();
  775. }
  776. });
  777. el.container.on('click.SelectPage', 'div.' + self.css_class.clear_btn, function (e) {
  778. e.stopPropagation();
  779. if (!self.disabled(self)) {
  780. self.clearAll(self, true);
  781. self.elem.hidden.change();
  782. if (p.eClear && $.isFunction(p.eClear)) p.eClear(self);
  783. }
  784. });
  785. el.result_area.on('mousedown.SelectPage', function (e) {
  786. e.stopPropagation();
  787. });
  788. if (p.multiple) {
  789. if (p.multipleControlbar) {
  790. //Select all item of current page
  791. el.control.find('.sp_select_all').on('click.SelectPage', function (e) {
  792. self.selectAllLine(self);
  793. }).hover(function () {
  794. el.control_text.html(msg.select_all);
  795. }, function () {
  796. el.control_text.html('');
  797. });
  798. //Cancel select all item of current page
  799. el.control.find('.sp_unselect_all').on('click.SelectPage', function (e) {
  800. self.unSelectAllLine(self);
  801. }).hover(function () {
  802. el.control_text.html(msg.unselect_all);
  803. }, function () {
  804. el.control_text.html('');
  805. });
  806. //Clear all selected item
  807. el.control.find('.sp_clear_all').on('click.SelectPage', function (e) {
  808. self.clearAll(self, true);
  809. }).hover(function () {
  810. el.control_text.html(msg.clear_all);
  811. }, function () {
  812. el.control_text.html('');
  813. });
  814. }
  815. el.element_box.on('click.SelectPage', function (e) {
  816. var srcEl = e.target || e.srcElement;
  817. if ($(srcEl).is('ul')) el.combo_input.focus();
  818. });
  819. //Tag close
  820. el.element_box.on('click.SelectPage', 'span.tag_close', function () {
  821. var li = $(this).closest('li'), data = li.data('dataObj');
  822. self.removeTag(self, li);
  823. showList();
  824. if (p.eTagRemove && $.isFunction(p.eTagRemove)) p.eTagRemove([data]);
  825. });
  826. self.inputResize(self);
  827. }
  828. };
  829. /**
  830. * Out of plugin area click event handler
  831. */
  832. SelectPage.prototype.eWhole = function () {
  833. var self = this, css = self.css_class;
  834. var cleanContent = function (obj) {
  835. obj.elem.combo_input.val('');
  836. if (!obj.option.multiple) obj.elem.hidden.val('');
  837. obj.prop.selected_text = '';
  838. };
  839. //Out of plugin area
  840. $(document.body).off('mousedown.selectPage').on('mousedown.selectPage', function (e) {
  841. var ele = e.target || e.srcElement;
  842. var sp = $(ele).closest('div.' + css.container);
  843. //Open status result list
  844. $('div.' + css.container + '.' + css.container_open).each(function () {
  845. if (this == sp[0]) return;
  846. var $this = $(this), d = $this.find('input.' + css.input).data(SelectPage.dataKey);
  847. if (!d.elem.combo_input.val() && d.elem.hidden.val() && !d.option.multiple) {
  848. d.prop.current_page = 1;//reset page to 1
  849. cleanContent(d);
  850. d.hideResults(d);
  851. return true;
  852. }
  853. if (d.elem.results.find('li').not('.' + css.message_box).length) {
  854. if (d.option.autoFillResult) {
  855. //have selected item, then hide result list
  856. if (d.elem.hidden.val()) d.hideResults(d);
  857. else if (d.elem.results.find('li.sp_over').length) {
  858. //no one selected and have highlight item, select the highlight item
  859. d.selectCurrentLine(d, true);
  860. } else if (d.option.autoSelectFirst) {
  861. //no one selected, no one highlight, select the first item
  862. d.nextLine(d);
  863. d.selectCurrentLine(d, true);
  864. } else d.hideResults(d);
  865. } else d.hideResults(d);
  866. } else {
  867. //when no one item match, clear search keywords
  868. if (d.option.noResultClean) cleanContent(d);
  869. else {
  870. if (!d.option.multiple) d.elem.hidden.val('');
  871. }
  872. d.hideResults(d);
  873. }
  874. });
  875. });
  876. };
  877. /**
  878. * Result list event bind
  879. */
  880. SelectPage.prototype.eResultList = function () {
  881. var self = this, css = this.css_class;
  882. self.elem.results.children('li').hover(function () {
  883. if (self.prop.key_select) {
  884. self.prop.key_select = false;
  885. return;
  886. }
  887. if (!$(this).hasClass(css.selected) && !$(this).hasClass(css.message_box)) {
  888. $(this).addClass(css.select);
  889. self.setCssFocusedResults(self);
  890. }
  891. }, function () {
  892. $(this).removeClass(css.select);
  893. }).click(function (e) {
  894. if (self.prop.key_select) {
  895. self.prop.key_select = false;
  896. return;
  897. }
  898. e.preventDefault();
  899. e.stopPropagation();
  900. if (!$(this).hasClass(css.selected)) self.selectCurrentLine(self, false);
  901. });
  902. };
  903. /**
  904. * Reposition result list when list beyond the visible area
  905. */
  906. SelectPage.prototype.eScroll = function () {
  907. var self = this, css = this.css_class;
  908. $(window).on('scroll.SelectPage', function (e) {
  909. $('div.' + css.container + '.' + css.container_open).each(function () {
  910. var $this = $(this), d = $this.find('input.' + css.input).data(SelectPage.dataKey),
  911. offset = d.elem.result_area.offset(),
  912. screenScrollTop = $(window).scrollTop(),
  913. docHeight = $(document).height(),
  914. viewHeight = $(window).height(),
  915. listHeight = d.elem.result_area.outerHeight(),
  916. listBottom = offset.top + listHeight,
  917. hasOverflow = docHeight > viewHeight,
  918. down = d.elem.result_area.hasClass('shadowDown');
  919. if (hasOverflow) {
  920. if (down) {//open down
  921. if (listBottom > (viewHeight + screenScrollTop)) d.calcResultsSize(d);
  922. } else {//open up
  923. if (offset.top < screenScrollTop) d.calcResultsSize(d);
  924. }
  925. }
  926. });
  927. });
  928. };
  929. /**
  930. * Page bar button event bind
  931. */
  932. SelectPage.prototype.ePaging = function () {
  933. var self = this;
  934. if (!self.option.pagination) return;
  935. self.elem.navi.find('li.csFirstPage').off('click').on('click', function (ev) {
  936. //$(self.elem.combo_input).focus();
  937. ev.preventDefault();
  938. self.firstPage(self);
  939. });
  940. self.elem.navi.find('li.csPreviousPage').off('click').on('click', function (ev) {
  941. //$(self.elem.combo_input).focus();
  942. ev.preventDefault();
  943. self.prevPage(self);
  944. });
  945. self.elem.navi.find('li.csNextPage').off('click').on('click', function (ev) {
  946. //$(self.elem.combo_input).focus();
  947. ev.preventDefault();
  948. self.nextPage(self);
  949. });
  950. self.elem.navi.find('li.csLastPage').off('click').on('click', function (ev) {
  951. //$(self.elem.combo_input).focus();
  952. ev.preventDefault();
  953. self.lastPage(self);
  954. });
  955. };
  956. /**
  957. * Ajax request fail
  958. * @param {Object} self
  959. * @param {string} errorThrown
  960. */
  961. SelectPage.prototype.ajaxErrorNotify = function (self, errorThrown) {
  962. self.showMessage(self, self.message.ajax_error);
  963. };
  964. /**
  965. * Message box
  966. * @param {Object} self
  967. * @param msg {string} the text need to show
  968. */
  969. SelectPage.prototype.showMessage = function (self, msg) {
  970. if (!msg) return;
  971. var msgLi = '<li class="' + self.css_class.message_box + '"><i class="spfont sp-warning"></i> ' + msg + '</li>';
  972. self.elem.results.empty().append(msgLi).show();
  973. self.calcResultsSize(self);
  974. self.setOpenStatus(self, true);
  975. if (self.elem.control) self.elem.control.hide();
  976. if (self.option.pagination) self.elem.navi.hide();
  977. };
  978. /**
  979. * @desc Scroll
  980. * @param {Object} self
  981. * @param {boolean} enforce
  982. */
  983. SelectPage.prototype.scrollWindow = function (self, enforce) {
  984. var current_result = self.getCurrentLine(self),
  985. target_top = (current_result && !enforce) ? current_result.offset().top : self.elem.container.offset().top,
  986. target_size;
  987. self.prop.size_li = self.elem.results.children('li:first').outerHeight();
  988. target_size = self.prop.size_li;
  989. var gap, client_height = $(window).height(),
  990. scroll_top = $(window).scrollTop(),
  991. scroll_bottom = scroll_top + client_height - target_size;
  992. if (current_result.length) {
  993. if (target_top < scroll_top || target_size > client_height) {
  994. //scroll to top
  995. gap = target_top - scroll_top;
  996. } else if (target_top > scroll_bottom) {
  997. //scroll down
  998. gap = target_top - scroll_bottom;
  999. } else return; //do not scroll
  1000. } else if (target_top < scroll_top) gap = target_top - scroll_top;
  1001. window.scrollBy(0, gap);
  1002. };
  1003. /**
  1004. * change css class by status
  1005. * @param self
  1006. * @param status {boolean} true: open, false: close
  1007. */
  1008. SelectPage.prototype.setOpenStatus = function (self, status) {
  1009. var el = self.elem, css = self.css_class;
  1010. if (status) {
  1011. el.container.addClass(css.container_open);
  1012. el.result_area.addClass(css.result_open);
  1013. } else {
  1014. el.container.removeClass(css.container_open);
  1015. el.result_area.removeClass(css.result_open);
  1016. }
  1017. };
  1018. /**
  1019. * input element in focus css class set
  1020. * @param {Object} self
  1021. */
  1022. SelectPage.prototype.setCssFocusedInput = function (self) {
  1023. //$(self.elem.results).addClass(self.css_class.re_off);
  1024. //$(self.elem.combo_input).removeClass(self.css_class.input_off);
  1025. };
  1026. /**
  1027. * set result list get focus and input element lost focus
  1028. * @param {Object} self
  1029. */
  1030. SelectPage.prototype.setCssFocusedResults = function (self) {
  1031. //$(self.elem.results).removeClass(self.css_class.re_off);
  1032. //$(self.elem.combo_input).addClass(self.css_class.input_off);
  1033. };
  1034. /**
  1035. * Quick search input keywords listener
  1036. * @param {Object} self
  1037. */
  1038. SelectPage.prototype.checkValue = function (self) {
  1039. var now_value = self.elem.combo_input.val();
  1040. if (now_value != self.prop.prev_value) {
  1041. self.prop.prev_value = now_value;
  1042. self.prop.first_show = false;
  1043. if (self.option.selectOnly) self.setButtonAttrDefault();
  1044. if (!self.option.multiple && !now_value) {
  1045. self.elem.combo_input.val('');
  1046. self.elem.hidden.val('');
  1047. self.elem.clear_btn.remove();
  1048. }
  1049. self.suggest(self);
  1050. }
  1051. };
  1052. /**
  1053. * Input handle(regular input)
  1054. * @param {Object} self
  1055. * @param {Object} e - event object
  1056. */
  1057. SelectPage.prototype.processKey = function (self, e) {
  1058. if ($.inArray(e.keyCode, [37, 38, 39, 40, 27, 9, 13]) === -1) {
  1059. if (e.keyCode != 16) self.setCssFocusedInput(self); // except Shift(16)
  1060. self.inputResize(self);
  1061. if ($.type(self.option.data) === 'string') {
  1062. self.prop.last_input_time = e.timeStamp;
  1063. setTimeout(function () {
  1064. if ((e.timeStamp - self.prop.last_input_time) === 0)
  1065. self.checkValue(self);
  1066. }, self.option.inputDelay * 1000);
  1067. } else {
  1068. self.checkValue(self);
  1069. }
  1070. }
  1071. }
  1072. /**
  1073. * Input handle(control key)
  1074. * @param {Object} self
  1075. * @param {Object} e - event object
  1076. */
  1077. SelectPage.prototype.processControl = function (self, e) {
  1078. if (($.inArray(e.keyCode, [37, 38, 39, 40, 27, 9]) > -1 && self.elem.result_area.is(':visible')) ||
  1079. ($.inArray(e.keyCode, [13, 9]) > -1 && self.getCurrentLine(self))) {
  1080. e.preventDefault();
  1081. e.stopPropagation();
  1082. e.cancelBubble = true;
  1083. e.returnValue = false;
  1084. switch (e.keyCode) {
  1085. case 37:// left
  1086. if (e.shiftKey) self.firstPage(self);
  1087. else self.prevPage(self);
  1088. break;
  1089. case 38:// up
  1090. self.prop.key_select = true;
  1091. self.prevLine(self);
  1092. break;
  1093. case 39:// right
  1094. if (e.shiftKey) self.lastPage(self);
  1095. else self.nextPage(self);
  1096. break;
  1097. case 40:// down
  1098. if (self.elem.results.children('li').length) {
  1099. self.prop.key_select = true;
  1100. self.nextLine(self);
  1101. } else self.suggest(self);
  1102. break;
  1103. case 9:// tab
  1104. self.prop.key_paging = true;
  1105. self.selectCurrentLine(self, true);
  1106. //self.hideResults(self);
  1107. break;
  1108. case 13:// return
  1109. self.selectCurrentLine(self, true);
  1110. break;
  1111. case 27:// escape
  1112. self.prop.key_paging = true;
  1113. self.hideResults(self);
  1114. break;
  1115. }
  1116. }
  1117. };
  1118. /**
  1119. * Abort Ajax request
  1120. * @param {Object} self
  1121. */
  1122. SelectPage.prototype.abortAjax = function (self) {
  1123. if (self.prop.xhr) {
  1124. self.prop.xhr.abort();
  1125. self.prop.xhr = false;
  1126. }
  1127. };
  1128. /**
  1129. * Suggest result of search keywords
  1130. * @param {Object} self
  1131. */
  1132. SelectPage.prototype.suggest = function (self) {
  1133. var q_word, val = $.trim(self.elem.combo_input.val());
  1134. if (self.option.multiple) q_word = val;
  1135. else {
  1136. if (val && val == self.prop.selected_text) q_word = '';
  1137. else q_word = val;
  1138. }
  1139. q_word = q_word.split(self.option.separator);
  1140. //Before show up result list callback
  1141. if (self.option.eOpen && $.isFunction(self.option.eOpen))
  1142. self.option.eOpen.call(self);
  1143. self.abortAjax(self);
  1144. //self.setLoading(self);
  1145. var which_page_num = self.prop.current_page || 1;
  1146. if (typeof self.option.data == 'object') self.searchForJson(self, q_word, which_page_num);
  1147. else self.searchForDb(self, q_word, which_page_num);
  1148. };
  1149. /**
  1150. * Loading
  1151. * @param {Object} self
  1152. */
  1153. SelectPage.prototype.setLoading = function (self) {
  1154. if (self.elem.results.html() === '') {
  1155. //self.calcResultsSize(self);
  1156. self.setOpenStatus(self, true);
  1157. }
  1158. };
  1159. /**
  1160. * Search for ajax
  1161. * @param {Object} self
  1162. * @param {Array} q_word - query keyword
  1163. * @param {number} which_page_num - target page number
  1164. */
  1165. SelectPage.prototype.searchForDb = function (self, q_word, which_page_num) {
  1166. var p = self.option;
  1167. if (!p.eAjaxSuccess || !$.isFunction(p.eAjaxSuccess)) self.hideResults(self);
  1168. var _paramsFunc = p.params, _params = {}, searchKey = p.searchField;
  1169. //when have new query keyword, then reset page number to 1.
  1170. if (q_word.length && q_word[0] && q_word.join(self.option.separator) !== self.prop.prev_value) which_page_num = 1;
  1171. var _orgParams = {
  1172. q_word: q_word,
  1173. pageNumber: which_page_num,
  1174. pageSize: p.pageSize,
  1175. andOr: p.andOr,
  1176. orderBy: p.orderBy,
  1177. searchTable: p.dbTable,
  1178. showField: self.option.showField,
  1179. keyField: self.option.keyField,
  1180. searchField: self.option.searchField
  1181. };
  1182. if (p.orderBy !== false) _orgParams.orderBy = p.orderBy;
  1183. // 这个应该是历史遗留了,没仔细追逻辑,先留着。
  1184. _orgParams[searchKey] = q_word[0];
  1185. if (_paramsFunc) {
  1186. var result = $.isFunction(_paramsFunc) ? _paramsFunc(self) : _paramsFunc;
  1187. if (result && $.isPlainObject(result)) {
  1188. _params = $.extend({}, _orgParams, result);
  1189. } else {
  1190. _params = _orgParams;
  1191. }
  1192. } else {
  1193. _params = _orgParams;
  1194. }
  1195. self.prop.xhr = $.ajax({
  1196. dataType: 'json',
  1197. url: p.data,
  1198. type: 'POST',
  1199. data: _params,
  1200. success: function (returnData) {
  1201. if (!returnData || !$.isPlainObject(returnData)) {
  1202. self.hideResults(self);
  1203. self.ajaxErrorNotify(self, errorThrown);
  1204. return;
  1205. }
  1206. var data = {}, json = {};
  1207. try {
  1208. data = p.eAjaxSuccess(returnData);
  1209. json.originalResult = data.list;
  1210. json.cnt_whole = data.totalRow;
  1211. } catch (e) {
  1212. self.showMessage(self, self.message.ajax_error);
  1213. return;
  1214. }
  1215. if (self.elem.navi) {
  1216. $(self.elem.navi).toggleClass("hide", json.cnt_whole <= json.originalResult.length);
  1217. }
  1218. json.candidate = [];
  1219. json.keyField = [];
  1220. if (typeof json.originalResult != 'object') {
  1221. self.prop.xhr = null;
  1222. self.notFoundSearch(self);
  1223. return;
  1224. }
  1225. json.cnt_page = json.originalResult.length;
  1226. for (var i = 0; i < json.cnt_page; i++) {
  1227. for (var key in json.originalResult[i]) {
  1228. if (key == p.keyField) {
  1229. json.keyField.push(json.originalResult[i][key]);
  1230. }
  1231. if (key == p.showField) {
  1232. json.candidate.push(json.originalResult[i][key]);
  1233. }
  1234. }
  1235. }
  1236. self.prepareResults(self, json, q_word, which_page_num);
  1237. },
  1238. error: function (jqXHR, textStatus, errorThrown) {
  1239. if (textStatus != 'abort') {
  1240. self.hideResults(self);
  1241. self.ajaxErrorNotify(self, errorThrown);
  1242. }
  1243. },
  1244. complete: function () {
  1245. self.prop.xhr = null;
  1246. }
  1247. });
  1248. };
  1249. /**
  1250. * Search for json data source
  1251. * @param {Object} self
  1252. * @param {Array} q_word
  1253. * @param {number} which_page_num
  1254. */
  1255. SelectPage.prototype.searchForJson = function (self, q_word, which_page_num) {
  1256. var p = self.option, matched = [], esc_q = [], sorted = [], json = {}, i = 0, arr_reg = [];
  1257. //query keyword filter
  1258. do {
  1259. //'/\W/g'正则代表全部不是字母,数字,下划线,汉字的字符
  1260. //将非法字符进行转义
  1261. esc_q[i] = q_word[i].replace(/\W/g, '\\$&').toString();
  1262. arr_reg[i] = new RegExp(esc_q[i], 'gi');
  1263. i++;
  1264. } while (i < q_word.length);
  1265. // SELECT * FROM data WHERE field LIKE q_word;
  1266. for (var i = 0; i < p.data.length; i++) {
  1267. var flag = false, row = p.data[i], itemText;
  1268. for (var j = 0; j < arr_reg.length; j++) {
  1269. itemText = row[p.searchField];
  1270. if (p.formatItem && $.isFunction(p.formatItem))
  1271. itemText = p.formatItem(row);
  1272. if (itemText.match(arr_reg[j])) {
  1273. flag = true;
  1274. if (p.andOr == 'OR') break;
  1275. } else {
  1276. flag = false;
  1277. if (p.andOr == 'AND') break;
  1278. }
  1279. }
  1280. if (flag) matched.push(row);
  1281. }
  1282. // (CASE WHEN ...) then く order some column
  1283. if (p.orderBy === false) sorted = matched.concat();
  1284. else {
  1285. var reg1 = new RegExp('^' + esc_q[0] + '$', 'gi'),
  1286. reg2 = new RegExp('^' + esc_q[0], 'gi'),
  1287. matched1 = [], matched2 = [], matched3 = [];
  1288. for (var i = 0; i < matched.length; i++) {
  1289. var orderField = p.orderBy[0][0];
  1290. var orderValue = String(matched[i][orderField]);
  1291. if (orderValue.match(reg1)) {
  1292. matched1.push(matched[i]);
  1293. } else if (orderValue.match(reg2)) {
  1294. matched2.push(matched[i]);
  1295. } else {
  1296. matched3.push(matched[i]);
  1297. }
  1298. }
  1299. if (p.orderBy[0][1].match(/^asc$/i)) {
  1300. matched1 = self.sortAsc(self, matched1);
  1301. matched2 = self.sortAsc(self, matched2);
  1302. matched3 = self.sortAsc(self, matched3);
  1303. } else {
  1304. matched1 = self.sortDesc(self, matched1);
  1305. matched2 = self.sortDesc(self, matched2);
  1306. matched3 = self.sortDesc(self, matched3);
  1307. }
  1308. sorted = sorted.concat(matched1).concat(matched2).concat(matched3);
  1309. }
  1310. /*
  1311. if (sorted.length === undefined || sorted.length === 0 ) {
  1312. self.notFoundSearch(self);
  1313. return;
  1314. }
  1315. */
  1316. json.cnt_whole = sorted.length;
  1317. //page_move used to distinguish between init plugin or page moving
  1318. if (!self.prop.page_move) {
  1319. //only single mode can be used page number relocation
  1320. if (!p.multiple) {
  1321. //get selected item belong page number
  1322. var currentValue = self.elem.hidden.val();
  1323. if ($.type(currentValue) !== 'undefined' && $.trim(currentValue) !== '') {
  1324. var index = 0;
  1325. $.each(sorted, function (i, row) {
  1326. if (row[p.keyField] == currentValue) {
  1327. index = i + 1;
  1328. return false;
  1329. }
  1330. });
  1331. which_page_num = Math.ceil(index / p.pageSize);
  1332. if (which_page_num < 1) which_page_num = 1;
  1333. self.prop.current_page = which_page_num;
  1334. }
  1335. }
  1336. } else {
  1337. //set page number to 1 when result number less then page size
  1338. if (sorted.length <= ((which_page_num - 1) * p.pageSize)) {
  1339. which_page_num = 1;
  1340. self.prop.current_page = 1;
  1341. }
  1342. }
  1343. //LIMIT xx OFFSET xx
  1344. var start = (which_page_num - 1) * p.pageSize, end = start + p.pageSize;
  1345. //save original data
  1346. json.originalResult = [];
  1347. //after data filter handle
  1348. for (var i = start; i < end; i++) {
  1349. if (sorted[i] === undefined) break;
  1350. json.originalResult.push(sorted[i]);
  1351. for (var key in sorted[i]) {
  1352. if (key == p.keyField) {
  1353. if (json.keyField === undefined) json.keyField = [];
  1354. json.keyField.push(sorted[i][key]);
  1355. }
  1356. if (key == p.showField) {
  1357. if (json.candidate === undefined) json.candidate = [];
  1358. json.candidate.push(sorted[i][key]);
  1359. }
  1360. }
  1361. }
  1362. if (json.candidate === undefined) json.candidate = [];
  1363. json.cnt_page = json.candidate.length;
  1364. self.prepareResults(self, json, q_word, which_page_num);
  1365. };
  1366. /**
  1367. * Set order asc
  1368. * @param {Object} self
  1369. * @param {Array} arr - result array
  1370. */
  1371. SelectPage.prototype.sortAsc = function (self, arr) {
  1372. arr.sort(function (a, b) {
  1373. var valA = a[self.option.orderBy[0][0]], valB = b[self.option.orderBy[0][0]];
  1374. return $.type(valA) === 'number' ? valA - valB : String(valA).localeCompare(String(valB));
  1375. });
  1376. return arr;
  1377. };
  1378. /**
  1379. * Set order desc
  1380. * @param {Object} self
  1381. * @param {Array} arr - result array
  1382. */
  1383. SelectPage.prototype.sortDesc = function (self, arr) {
  1384. arr.sort(function (a, b) {
  1385. var valA = a[self.option.orderBy[0][0]], valB = b[self.option.orderBy[0][0]];
  1386. return $.type(valA) === 'number' ? valB - valA : String(valB).localeCompare(String(valA));
  1387. });
  1388. return arr;
  1389. };
  1390. /**
  1391. * Not result found handle
  1392. * @param {Object} self
  1393. */
  1394. SelectPage.prototype.notFoundSearch = function (self) {
  1395. self.elem.results.empty();
  1396. self.calcResultsSize(self);
  1397. self.setOpenStatus(self, true);
  1398. self.setCssFocusedInput(self);
  1399. };
  1400. /**
  1401. * Prepare data to show
  1402. * @param {Object} self
  1403. * @param {Object} json - data result
  1404. * @param {Array} q_word - query keyword
  1405. * @param {number} which_page_num - target page number
  1406. */
  1407. SelectPage.prototype.prepareResults = function (self, json, q_word, which_page_num) {
  1408. self.data = json.originalResult;
  1409. if (self.option.pagination) self.setNavi(self, json.cnt_whole, json.cnt_page, which_page_num);
  1410. if (!json.keyField) json.keyField = false;
  1411. if (self.option.selectOnly && json.candidate.length === 1 && json.candidate[0] == q_word[0]) {
  1412. self.elem.hidden.val(json.keyField[0]);
  1413. this.setButtonAttrDefault();
  1414. }
  1415. var is_query = false;
  1416. if (q_word && q_word.length && q_word[0]) is_query = true;
  1417. self.displayResults(self, json, is_query);
  1418. };
  1419. /**
  1420. * Build page bar
  1421. * @param {Object} self
  1422. * @param {number} cnt_whole - total record count
  1423. * @param {number} cnt_page
  1424. * @param {number} page_num - current page number
  1425. */
  1426. SelectPage.prototype.setNavi = function (self, cnt_whole, cnt_page, page_num) {
  1427. var msg = self.message;
  1428. /**
  1429. * build pagination bar
  1430. */
  1431. var buildPageNav = function (self, pagebar, page_num, last_page) {
  1432. var updatePageInfo = function () {
  1433. var pageInfo = msg.page_info;
  1434. return pageInfo.replace(self.template.page.current, page_num).replace(self.template.page.total, last_page);
  1435. };
  1436. if (pagebar.find('li').length === 0) {
  1437. pagebar.hide().empty();
  1438. var iconFist = 'spfont sp-first',
  1439. iconPrev = 'spfont sp-previous',
  1440. iconNext = 'spfont sp-next',
  1441. iconLast = 'spfont sp-last';
  1442. pagebar.append('<li class="csFirstPage" title="' + msg.first_title + '" ><a href="javascript:void(0);"> <i class="' + iconFist + '"></i> </a></li>');
  1443. pagebar.append('<li class="csPreviousPage" title="' + msg.prev_title + '" ><a href="javascript:void(0);"><i class="' + iconPrev + '"></i></a></li>');
  1444. //pagination information
  1445. pagebar.append('<li class="pageInfoBox"><a href="javascript:void(0);"> ' + updatePageInfo() + ' </a></li>');
  1446. pagebar.append('<li class="csNextPage" title="' + msg.next_title + '" ><a href="javascript:void(0);"><i class="' + iconNext + '"></i></a></li>');
  1447. pagebar.append('<li class="csLastPage" title="' + msg.last_title + '" ><a href="javascript:void(0);"> <i class="' + iconLast + '"></i> </a></li>');
  1448. pagebar.show();
  1449. } else {
  1450. pagebar.find('li.pageInfoBox a').html(updatePageInfo());
  1451. }
  1452. };
  1453. var pagebar = self.elem.navi.find('ul'),
  1454. last_page = Math.ceil(cnt_whole / self.option.pageSize); //calculate total page
  1455. if (last_page === 0) page_num = 0;
  1456. else {
  1457. if (last_page < page_num) page_num = last_page;
  1458. else if (page_num === 0) page_num = 1;
  1459. }
  1460. self.prop.current_page = page_num;//update current page number
  1461. self.prop.max_page = last_page;//update page count
  1462. buildPageNav(self, pagebar, page_num, last_page);
  1463. //update paging status
  1464. var dClass = 'disabled',
  1465. first = pagebar.find('li.csFirstPage'),
  1466. previous = pagebar.find('li.csPreviousPage'),
  1467. next = pagebar.find('li.csNextPage'),
  1468. last = pagebar.find('li.csLastPage');
  1469. //first and previous
  1470. if (page_num === 1 || page_num === 0) {
  1471. if (!first.hasClass(dClass)) first.addClass(dClass);
  1472. if (!previous.hasClass(dClass)) previous.addClass(dClass);
  1473. } else {
  1474. if (first.hasClass(dClass)) first.removeClass(dClass);
  1475. if (previous.hasClass(dClass)) previous.removeClass(dClass);
  1476. }
  1477. //next and last
  1478. if (page_num === last_page || last_page === 0) {
  1479. if (!next.hasClass(dClass)) next.addClass(dClass);
  1480. if (!last.hasClass(dClass)) last.addClass(dClass);
  1481. } else {
  1482. if (next.hasClass(dClass)) next.removeClass(dClass);
  1483. if (last.hasClass(dClass)) last.removeClass(dClass);
  1484. }
  1485. if (last_page > 1) self.ePaging(); //pagination event bind
  1486. };
  1487. /**
  1488. * Render result list
  1489. * @param {Object} self
  1490. * @param {Object} json - result data
  1491. * @param {boolean} is_query - used to different from search to open and just click to open
  1492. */
  1493. SelectPage.prototype.displayResults = function (self, json, is_query) {
  1494. var p = self.option, el = self.elem;
  1495. el.results.hide().empty();
  1496. if (p.multiple && $.type(p.maxSelectLimit) === 'number' && p.maxSelectLimit > 0) {
  1497. var selectedSize = el.element_box.find('li.selected_tag').length;
  1498. if (selectedSize > 0 && selectedSize >= p.maxSelectLimit) {
  1499. var msg = self.message.max_selected;
  1500. self.showMessage(self, msg.replace(self.template.msg.maxSelectLimit, p.maxSelectLimit));
  1501. return;
  1502. }
  1503. }
  1504. if (json.candidate.length) {
  1505. var arr_candidate = json.candidate,
  1506. arr_primary_key = json.keyField,
  1507. keystr = el.hidden.val(),
  1508. keyArr = keystr ? keystr.split(',') : [],
  1509. itemText = '';
  1510. for (var i = 0; i < arr_candidate.length; i++) {
  1511. if (p.formatItem && $.isFunction(p.formatItem)) {
  1512. try {
  1513. itemText = p.formatItem(json.originalResult[i]);
  1514. } catch (e) {
  1515. console.error('formatItem内容格式化函数内容设置不正确!');
  1516. itemText = p.escape ? self.escapeHTML(arr_candidate[i]) : arr_candidate[i];
  1517. }
  1518. } else {
  1519. itemText = p.escape ? self.escapeHTML(arr_candidate[i]) : arr_candidate[i];
  1520. }
  1521. var list = $('<li>').html(itemText).attr({
  1522. pkey: arr_primary_key[i],
  1523. index: i
  1524. });
  1525. if (!p.formatItem) list.attr('title', itemText);
  1526. //Set selected item highlight
  1527. if ($.inArray(arr_primary_key[i].toString(), keyArr) !== -1) {
  1528. list.addClass(self.css_class.selected);
  1529. }
  1530. //cache item data
  1531. list.data('dataObj', json.originalResult[i]);
  1532. el.results.append(list);
  1533. }
  1534. } else {
  1535. var li = '<li class="' + self.css_class.message_box + '"><i class="spfont sp-warning"></i> ' +
  1536. self.message.not_found + '</li>';
  1537. el.results.append(li);
  1538. }
  1539. el.results.show();
  1540. if (p.multiple && p.multipleControlbar) el.control.show();
  1541. if (p.pagination) el.navi.show();
  1542. self.calcResultsSize(self);
  1543. self.setOpenStatus(self, true);
  1544. //Result item event bind
  1545. self.eResultList();
  1546. //scrolling listen
  1547. self.eScroll();
  1548. //auto highlight first item in search, have result and set autoSelectFirst to true situation
  1549. if (is_query && json.candidate.length && p.autoSelectFirst) self.nextLine(self);
  1550. };
  1551. /**
  1552. * Calculate result list size and position
  1553. * @param {Object} self
  1554. */
  1555. SelectPage.prototype.calcResultsSize = function (self) {
  1556. var p = self.option, el = self.elem;
  1557. var rePosition = function () {
  1558. if (el.container.css('position') === 'static') {
  1559. // position: static
  1560. var offset = el.combo_input.offset();
  1561. el.result_area.css({
  1562. top: offset.top + el.combo_input.outerHeight() + 'px',
  1563. left: offset.left + 'px'
  1564. });
  1565. } else {
  1566. if (!p.pagination) {
  1567. var itemHeight = el.results.find('li:first').outerHeight(true),
  1568. listHeight = itemHeight * p.listSize;
  1569. el.results.css({
  1570. 'max-height': listHeight,
  1571. 'overflow-y': 'auto'
  1572. });
  1573. }
  1574. //handle result list show up side(left, right, up or down)
  1575. var docWidth = $(document).width(),
  1576. docHeight = $(document).height(), //the document full height
  1577. viewHeight = $(window).height(), //browser visible area height
  1578. offset = el.container.offset(),
  1579. screenScrollTop = $(window).scrollTop(),
  1580. listWidth = el.result_area.outerWidth(),
  1581. //result list height
  1582. listHeight = el.result_area.outerHeight(),
  1583. //default left used input element left
  1584. defaultLeft = offset.left, //p.multiple ? -1 : 0;
  1585. //input element height
  1586. inputHeight = el.container.outerHeight(),
  1587. left = (offset.left + listWidth) > docWidth ?
  1588. defaultLeft - (listWidth - el.container.outerWidth()) :
  1589. defaultLeft,
  1590. //the actual top coordinate of input element(outer div)
  1591. screenTop = offset.top, //$(el.container).scrollTop();//offset.top - screenScrollTop;
  1592. top = 0, dist = 5, //set distance between input element and result list
  1593. //the actual top coordinate of result list
  1594. listBottom = screenTop + inputHeight + listHeight + dist,
  1595. listTop = screenTop + listHeight + dist,
  1596. hasOverflow = docHeight > viewHeight;
  1597. if ((screenTop - screenScrollTop - dist > listHeight) &&
  1598. (hasOverflow && listBottom > (viewHeight + screenScrollTop)) ||
  1599. (!hasOverflow && listBottom > viewHeight && screenTop >= listTop)) {
  1600. //open up
  1601. top = offset.top - listHeight - dist;
  1602. el.result_area.removeClass('shadowUp shadowDown').addClass('shadowUp');
  1603. } else {
  1604. //open down
  1605. top = offset.top + (p.multiple ? el.container.outerHeight() : inputHeight);
  1606. el.result_area.removeClass('shadowUp shadowDown').addClass('shadowDown');
  1607. top += dist;
  1608. }
  1609. return {
  1610. top: top + 'px', left: left + 'px'
  1611. };
  1612. }
  1613. };
  1614. if (el.result_area.is(':visible')) {
  1615. el.result_area.css(rePosition());
  1616. } else {
  1617. var pss = rePosition();
  1618. el.result_area.css(pss).show(1, function () {
  1619. var repss = rePosition();
  1620. if (pss.top !== repss.top || pss.left !== repss.left) el.result_area.css(repss);
  1621. });
  1622. }
  1623. };
  1624. /**
  1625. * hide result list
  1626. * @param {Object} self
  1627. */
  1628. SelectPage.prototype.hideResults = function (self) {
  1629. if (self.prop.key_paging) {
  1630. self.scrollWindow(self, true);
  1631. self.prop.key_paging = false;
  1632. }
  1633. self.setCssFocusedInput(self);
  1634. if (self.option.autoFillResult) {
  1635. //self.selectCurrentLine(self, true);
  1636. }
  1637. self.elem.results.empty();
  1638. self.elem.result_area.hide();
  1639. self.setOpenStatus(self, false);
  1640. //unbind window scroll listen
  1641. $(window).off('scroll.SelectPage');
  1642. self.abortAjax(self);
  1643. self.setButtonAttrDefault();
  1644. };
  1645. /**
  1646. * set plugin to disabled / enabled
  1647. * @param self
  1648. * @param disabled
  1649. */
  1650. SelectPage.prototype.disabled = function (self, disabled) {
  1651. var p = self.option, el = self.elem;
  1652. if ($.type(disabled) === 'undefined') return el.combo_input.prop('disabled');
  1653. if ($.type(disabled) === 'boolean') {
  1654. el.combo_input.prop('disabled', disabled);
  1655. if (disabled) el.container.addClass(self.css_class.disabled);
  1656. else el.container.removeClass(self.css_class.disabled);
  1657. }
  1658. };
  1659. /**
  1660. * Go fist page
  1661. * @param {Object} self
  1662. */
  1663. SelectPage.prototype.firstPage = function (self) {
  1664. if (self.prop.current_page > 1) {
  1665. self.prop.current_page = 1;
  1666. self.prop.page_move = true;
  1667. self.suggest(self);
  1668. }
  1669. };
  1670. /**
  1671. * Go previous page
  1672. * @param {Object} self
  1673. */
  1674. SelectPage.prototype.prevPage = function (self) {
  1675. if (self.prop.current_page > 1) {
  1676. self.prop.current_page--;
  1677. self.prop.page_move = true;
  1678. self.suggest(self);
  1679. }
  1680. };
  1681. /**
  1682. * Go next page
  1683. * @param {Object} self
  1684. */
  1685. SelectPage.prototype.nextPage = function (self) {
  1686. if (self.prop.current_page < self.prop.max_page) {
  1687. self.prop.current_page++;
  1688. self.prop.page_move = true;
  1689. self.suggest(self);
  1690. }
  1691. };
  1692. /**
  1693. * Go last page
  1694. * @param {Object} self
  1695. */
  1696. SelectPage.prototype.lastPage = function (self) {
  1697. if (self.prop.current_page < self.prop.max_page) {
  1698. self.prop.current_page = self.prop.max_page;
  1699. self.prop.page_move = true;
  1700. self.suggest(self);
  1701. }
  1702. };
  1703. /**
  1704. * do something after select/unSelect action
  1705. * @param {Object} self
  1706. * @param {boolean} reOpen
  1707. */
  1708. SelectPage.prototype.afterAction = function (self, reOpen) {
  1709. self.inputResize(self);
  1710. self.elem.combo_input.change();
  1711. self.setCssFocusedInput(self);
  1712. if (self.prop.init_set) return;
  1713. if (self.option.multiple) {
  1714. if (self.option.selectToCloseList) {
  1715. self.hideResults(self);
  1716. self.elem.combo_input.blur();
  1717. }
  1718. if (!self.option.selectToCloseList && reOpen) {
  1719. self.suggest(self);
  1720. self.elem.combo_input.focus();
  1721. }
  1722. } else {
  1723. self.hideResults(self);
  1724. self.elem.combo_input.blur();
  1725. }
  1726. };
  1727. /**
  1728. * Select current list item
  1729. * @param {Object} self
  1730. * @param {boolean} is_enter_key
  1731. */
  1732. SelectPage.prototype.selectCurrentLine = function (self, is_enter_key) {
  1733. self.scrollWindow(self, true);
  1734. var p = self.option, current = self.getCurrentLine(self);
  1735. if (current) {
  1736. var data = current.data('dataObj');
  1737. var text = data[p.showField] || current.text();
  1738. var value = current.attr('pkey');
  1739. if (!p.multiple) {
  1740. self.elem.combo_input.val(text);
  1741. self.elem.hidden.val(value);
  1742. } else {
  1743. //build tags in multiple selection mode
  1744. self.elem.combo_input.val('');
  1745. var item = {text: text, value: value};
  1746. if (!self.isAlreadySelected(self, item)) {
  1747. self.addNewTag(self, data, item);
  1748. self.tagValuesSet(self);
  1749. }
  1750. }
  1751. if (p.selectOnly) self.setButtonAttrDefault();
  1752. //Select item callback
  1753. if (p.eSelect && $.isFunction(p.eSelect)) p.eSelect(data, self);
  1754. self.prop.prev_value = self.elem.combo_input.val();
  1755. self.prop.selected_text = self.elem.combo_input.val();
  1756. self.putClearButton();
  1757. }
  1758. self.afterAction(self, true);
  1759. };
  1760. /**
  1761. * Show clear button when item selected in single selection mode
  1762. */
  1763. SelectPage.prototype.putClearButton = function () {
  1764. if (!this.option.multiple && !this.elem.combo_input.prop('disabled')) this.elem.container.append(this.elem.clear_btn);
  1765. };
  1766. /**
  1767. * Select all list item
  1768. * @param {Object} self
  1769. */
  1770. SelectPage.prototype.selectAllLine = function (self) {
  1771. var p = self.option, jsonarr = new Array();
  1772. self.elem.results.find('li').each(function (i, row) {
  1773. var $row = $(row), data = $row.data('dataObj');
  1774. var text = data[p.showField] || $row.text();
  1775. var value = $row.attr('pkey');
  1776. var item = {text: text, value: value};
  1777. if (!self.isAlreadySelected(self, item)) {
  1778. self.addNewTag(self, data, item);
  1779. self.tagValuesSet(self);
  1780. }
  1781. jsonarr.push(data);
  1782. //limited max selected items
  1783. if ($.type(p.maxSelectLimit) === 'number' &&
  1784. p.maxSelectLimit > 0 &&
  1785. p.maxSelectLimit === self.elem.element_box.find('li.selected_tag').length) {
  1786. return false;
  1787. }
  1788. });
  1789. if (p.eSelect && $.isFunction(p.eSelect)) p.eSelect(jsonarr, self);
  1790. self.afterAction(self, true);
  1791. };
  1792. /**
  1793. * Cancel select all item in current page
  1794. * @param {Object} self
  1795. */
  1796. SelectPage.prototype.unSelectAllLine = function (self) {
  1797. var p = self.option, size = self.elem.results.find('li').length, ds = [];
  1798. self.elem.results.find('li').each(function (i, row) {
  1799. var key = $(row).attr('pkey');
  1800. var tag = self.elem.element_box.find('li.selected_tag[itemvalue="' + key + '"]');
  1801. if (tag.length) ds.push(tag.data('dataObj'));
  1802. self.removeTag(self, tag);
  1803. });
  1804. self.afterAction(self, true);
  1805. if (p.eTagRemove && $.isFunction(p.eTagRemove)) p.eTagRemove(ds);
  1806. };
  1807. /**
  1808. * Clear all selected items
  1809. * @param {Object} self
  1810. * @param {boolean} open - open list after clear selected item
  1811. */
  1812. SelectPage.prototype.clearAll = function (self, open) {
  1813. var p = self.option, ds = [];
  1814. if (p.multiple) {
  1815. self.elem.element_box.find('li.selected_tag').each(function (i, row) {
  1816. ds.push($(row).data('dataObj'));
  1817. row.remove();
  1818. });
  1819. self.elem.element_box.find('li.selected_tag').remove();
  1820. }
  1821. self.reset(self);
  1822. self.afterAction(self, open);
  1823. if (p.multiple) {
  1824. if (p.eTagRemove && $.isFunction(p.eTagRemove)) p.eTagRemove(ds);
  1825. } else self.elem.clear_btn.remove();
  1826. };
  1827. /**
  1828. * reset
  1829. */
  1830. SelectPage.prototype.reset = function (self) {
  1831. self.elem.combo_input.val('');
  1832. self.elem.hidden.val('');
  1833. self.prop.prev_value = '';
  1834. self.prop.selected_text = '';
  1835. self.prop.current_page = 1;
  1836. };
  1837. /**
  1838. * Get current highlight item
  1839. * @param {Object} self
  1840. */
  1841. SelectPage.prototype.getCurrentLine = function (self) {
  1842. if (self.elem.result_area.is(':hidden')) return false;
  1843. var obj = self.elem.results.find('li.' + self.css_class.select);
  1844. if (obj.length) return obj;
  1845. else return false;
  1846. };
  1847. /**
  1848. * Check the result item is already selected or not
  1849. * @param {Object} self
  1850. * @param {Object} item - item info
  1851. */
  1852. SelectPage.prototype.isAlreadySelected = function (self, item) {
  1853. var isExist = false;
  1854. if (item.value) {
  1855. var keys = self.elem.hidden.val();
  1856. if (keys) {
  1857. var karr = keys.split(',');
  1858. if (karr && karr.length && $.inArray(item.value, karr) != -1) isExist = true;
  1859. }
  1860. }
  1861. return isExist;
  1862. };
  1863. /**
  1864. * Add a new tag in multiple selection mode
  1865. * @param {Object} self
  1866. * @param {object} data - raw row data
  1867. * @param {Object} item
  1868. */
  1869. SelectPage.prototype.addNewTag = function (self, data, item) {
  1870. if (!self.option.multiple || !data || !item) return;
  1871. var tmp = self.template.tag.content, tag;
  1872. tmp = tmp.replace(self.template.tag.textKey, item.text);
  1873. tmp = tmp.replace(self.template.tag.valueKey, item.value);
  1874. tag = $(tmp);
  1875. tag.data('dataObj', data);
  1876. if (self.elem.combo_input.prop('disabled')) tag.find('span.tag_close').hide();
  1877. self.elem.combo_input.closest('li').before(tag);
  1878. };
  1879. /**
  1880. * Remove a tag in multiple selection mode
  1881. * @param {Object} self
  1882. * @param {Object} item
  1883. */
  1884. SelectPage.prototype.removeTag = function (self, item) {
  1885. var key = $(item).attr('itemvalue');
  1886. var keys = self.elem.hidden.val();
  1887. if ($.type(key) != 'undefined' && keys) {
  1888. var keyarr = keys.split(','),
  1889. index = $.inArray(key.toString(), keyarr);
  1890. if (index != -1) {
  1891. keyarr.splice(index, 1);
  1892. self.elem.hidden.val(keyarr.toString()).trigger("change");
  1893. }
  1894. }
  1895. $(item).remove();
  1896. self.inputResize(self);
  1897. };
  1898. /**
  1899. * Selected item value(keyField) put in to hidden element
  1900. * @param {Object} self
  1901. */
  1902. SelectPage.prototype.tagValuesSet = function (self) {
  1903. if (!self.option.multiple) return;
  1904. var tags = self.elem.element_box.find('li.selected_tag');
  1905. if (tags && tags.length) {
  1906. var result = new Array();
  1907. $.each(tags, function (i, li) {
  1908. var v = $(li).attr('itemvalue');
  1909. if ($.type(v) !== 'undefined') result.push(v);
  1910. });
  1911. if (result.length) {
  1912. self.elem.hidden.val(result.join(',')).trigger("change");
  1913. }
  1914. }
  1915. };
  1916. /**
  1917. * auto resize input element width in multiple select mode
  1918. * @param {Object} self
  1919. */
  1920. SelectPage.prototype.inputResize = function (self) {
  1921. if (!self.option.multiple) return;
  1922. var width = '',
  1923. inputLi = self.elem.combo_input.closest('li');
  1924. var setDefaultSize = function (self, inputLi) {
  1925. inputLi.removeClass('full_width');
  1926. var minimumWidth = self.elem.combo_input.val().length + 1,
  1927. width = (minimumWidth * 0.75) + 'em';
  1928. self.elem.combo_input.css('width', width).removeAttr('placeholder');
  1929. };
  1930. if (self.elem.element_box.find('li.selected_tag').length === 0) {
  1931. if (!inputLi.hasClass('full_width')) inputLi.addClass('full_width');
  1932. if (self.elem.combo_input.attr('placeholder_bak')) {
  1933. self.elem.combo_input.attr('placeholder', self.elem.combo_input.attr('placeholder_bak')).removeAttr('style');
  1934. }
  1935. } else setDefaultSize(self, inputLi);
  1936. };
  1937. /**
  1938. * Move to next line
  1939. * @param {Object} self
  1940. */
  1941. SelectPage.prototype.nextLine = function (self) {
  1942. var obj = self.getCurrentLine(self), idx;
  1943. if (!obj) idx = -1;
  1944. else {
  1945. idx = self.elem.results.children('li').index(obj);
  1946. obj.removeClass(self.css_class.select);
  1947. }
  1948. idx++;
  1949. if (idx < self.elem.results.children('li').length) {
  1950. var next = self.elem.results.children('li').eq(idx);
  1951. next.addClass(self.css_class.select);
  1952. self.setCssFocusedResults(self);
  1953. } else self.setCssFocusedInput(self);
  1954. self.scrollWindow(self, false);
  1955. };
  1956. /**
  1957. * Move to previous line
  1958. * @param {Object} self
  1959. */
  1960. SelectPage.prototype.prevLine = function (self) {
  1961. var obj = self.getCurrentLine(self), idx;
  1962. if (!obj) idx = self.elem.results.children('li').length;
  1963. else {
  1964. idx = self.elem.results.children('li').index(obj);
  1965. obj.removeClass(self.css_class.select);
  1966. }
  1967. idx--;
  1968. if (idx > -1) {
  1969. var prev = self.elem.results.children('li').eq(idx);
  1970. prev.addClass(self.css_class.select);
  1971. self.setCssFocusedResults(self);
  1972. } else self.setCssFocusedInput(self);
  1973. self.scrollWindow(self, false);
  1974. };
  1975. /**
  1976. * SelectPage plugin definition
  1977. * @global
  1978. * @param option {Object} init plugin option
  1979. */
  1980. function Plugin(option) {
  1981. return this.each(function () {
  1982. var $this = $(this),
  1983. data = $this.data(SelectPage.dataKey),
  1984. params = $.extend({}, defaults, $this.data(), data && data.option, typeof option === 'object' && option);
  1985. if (!data) $this.data(SelectPage.dataKey, (data = new SelectPage(this, params)));
  1986. });
  1987. }
  1988. /**
  1989. * Get plugin object
  1990. * @param {object} obj
  1991. * @returns
  1992. */
  1993. function getPlugin(obj) {
  1994. return $(obj).closest('div.sp_container').find('input.sp_input');
  1995. }
  1996. /**
  1997. * Clear all selected item
  1998. */
  1999. function ClearSelected() {
  2000. return this.each(function () {
  2001. var $this = getPlugin(this),
  2002. data = $this.data(SelectPage.dataKey);
  2003. if (data) {
  2004. data.prop.init_set = true;
  2005. data.clearAll(data);
  2006. data.prop.init_set = false;
  2007. }
  2008. });
  2009. }
  2010. /**
  2011. * Refresh result list
  2012. * use case:
  2013. * 1.use $(obj).val('xxx') to modify selectpage selected item key
  2014. * 2.refresh selected item show content/tag text
  2015. */
  2016. function SelectedRefresh() {
  2017. return this.each(function () {
  2018. var $this = getPlugin(this),
  2019. data = $this.data(SelectPage.dataKey);
  2020. if (data && data.elem.hidden.val())
  2021. data.setInitRecord(true);
  2022. });
  2023. }
  2024. /**
  2025. * Modify plugin datasource, only work on json datasource mode
  2026. * @param {array} data - new datasource
  2027. * @example
  2028. * [{name:'aa',sex:1},{name:'bb',sex:0},{...}]
  2029. */
  2030. function ModifyDataSource(data) {
  2031. return this.each(function () {
  2032. if (data && $.isArray(data)) {
  2033. var $this = getPlugin(this),
  2034. plugin = $this.data(SelectPage.dataKey);
  2035. if (plugin) {
  2036. plugin.clearAll(plugin);
  2037. plugin.option.data = data;
  2038. }
  2039. }
  2040. });
  2041. }
  2042. /**
  2043. * Get plugin disabled status or Modify plugin disabled status
  2044. * @param disabled {boolean} set disabled status
  2045. */
  2046. function PluginDisabled(disabled) {
  2047. var status = false;
  2048. this.each(function () {
  2049. var $this = getPlugin(this),
  2050. plugin = $this.data(SelectPage.dataKey);
  2051. if (plugin) {
  2052. if ($.type(disabled) !== 'undefined')
  2053. plugin.disabled(plugin, disabled);
  2054. else
  2055. status = plugin.disabled(plugin);
  2056. }
  2057. });
  2058. return status;
  2059. }
  2060. /**
  2061. * Get selected item text
  2062. * @returns {string}
  2063. */
  2064. function GetInputText() {
  2065. var str = '';
  2066. this.each(function () {
  2067. var $this = getPlugin(this), data = $this.data(SelectPage.dataKey);
  2068. if (data) {
  2069. if (data.option.multiple) {
  2070. var tags = [];
  2071. data.elem.element_box.find('li.selected_tag').each(function (i, tag) {
  2072. tags.push($(tag).text());
  2073. });
  2074. str += tags.toString();
  2075. } else {
  2076. str += data.elem.combo_input.val();
  2077. }
  2078. }
  2079. });
  2080. return str;
  2081. }
  2082. /**
  2083. * Get selected item raw data
  2084. * @returns {any[]}
  2085. */
  2086. function GetSelectedData() {
  2087. var results = [];
  2088. this.each(function () {
  2089. var $this = getPlugin(this), data = $this.data(SelectPage.dataKey);
  2090. if (data) {
  2091. if (data.option.multiple) {
  2092. data.elem.element_box.find('li.selected_tag').each(function (i, tag) {
  2093. results.push($(tag).data('dataObj'));
  2094. });
  2095. } else {
  2096. var selected = data.elem.combo_input.data('dataObj');
  2097. if (selected) results.push(selected);
  2098. }
  2099. }
  2100. });
  2101. return results;
  2102. }
  2103. var old = $.fn.selectPage;
  2104. $.fn.selectPage = Plugin;
  2105. $.fn.selectPage.Constructor = SelectPage;
  2106. $.fn.selectPageClear = ClearSelected;
  2107. $.fn.selectPageRefresh = SelectedRefresh;
  2108. $.fn.selectPageData = ModifyDataSource;
  2109. $.fn.selectPageDisabled = PluginDisabled;
  2110. $.fn.selectPageText = GetInputText;
  2111. $.fn.selectPageSelectedData = GetSelectedData;
  2112. // SelectPage no conflict
  2113. // =================
  2114. $.fn.selectPage.noConflict = function () {
  2115. $.fn.selectPage = old;
  2116. return this;
  2117. };
  2118. })(window.jQuery);