selectpage.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258
  1. /**
  2. * @summary SelectPage
  3. * @desc Simple and powerful selection plugin
  4. * @file selectpage.js
  5. * @version 2.21
  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. self.prop.current_page = 1;
  1044. if (self.option.selectOnly) self.setButtonAttrDefault();
  1045. if (!self.option.multiple && !now_value) {
  1046. self.elem.combo_input.val('');
  1047. self.elem.hidden.val('');
  1048. self.elem.clear_btn.remove();
  1049. }
  1050. self.suggest(self);
  1051. }
  1052. };
  1053. /**
  1054. * Input handle(regular input)
  1055. * @param {Object} self
  1056. * @param {Object} e - event object
  1057. */
  1058. SelectPage.prototype.processKey = function (self, e) {
  1059. if ($.inArray(e.keyCode, [37, 38, 39, 40, 27, 9, 13]) === -1) {
  1060. if (e.keyCode != 16) self.setCssFocusedInput(self); // except Shift(16)
  1061. self.inputResize(self);
  1062. if ($.type(self.option.data) === 'string') {
  1063. self.prop.last_input_time = e.timeStamp;
  1064. setTimeout(function () {
  1065. if ((e.timeStamp - self.prop.last_input_time) === 0)
  1066. self.checkValue(self);
  1067. }, self.option.inputDelay * 1000);
  1068. } else {
  1069. self.checkValue(self);
  1070. }
  1071. }
  1072. }
  1073. /**
  1074. * Input handle(control key)
  1075. * @param {Object} self
  1076. * @param {Object} e - event object
  1077. */
  1078. SelectPage.prototype.processControl = function (self, e) {
  1079. if (($.inArray(e.keyCode, [37, 38, 39, 40, 27, 9]) > -1 && self.elem.result_area.is(':visible')) ||
  1080. ($.inArray(e.keyCode, [13, 9]) > -1 && self.getCurrentLine(self))) {
  1081. e.preventDefault();
  1082. e.stopPropagation();
  1083. e.cancelBubble = true;
  1084. e.returnValue = false;
  1085. switch (e.keyCode) {
  1086. case 37:// left
  1087. if (e.shiftKey) self.firstPage(self);
  1088. else self.prevPage(self);
  1089. break;
  1090. case 38:// up
  1091. self.prop.key_select = true;
  1092. self.prevLine(self);
  1093. break;
  1094. case 39:// right
  1095. if (e.shiftKey) self.lastPage(self);
  1096. else self.nextPage(self);
  1097. break;
  1098. case 40:// down
  1099. if (self.elem.results.children('li').length) {
  1100. self.prop.key_select = true;
  1101. self.nextLine(self);
  1102. } else self.suggest(self);
  1103. break;
  1104. case 9:// tab
  1105. self.prop.key_paging = true;
  1106. self.selectCurrentLine(self, true);
  1107. //self.hideResults(self);
  1108. break;
  1109. case 13:// return
  1110. self.selectCurrentLine(self, true);
  1111. break;
  1112. case 27:// escape
  1113. self.prop.key_paging = true;
  1114. self.hideResults(self);
  1115. break;
  1116. }
  1117. }
  1118. };
  1119. /**
  1120. * Abort Ajax request
  1121. * @param {Object} self
  1122. */
  1123. SelectPage.prototype.abortAjax = function (self) {
  1124. if (self.prop.xhr) {
  1125. self.prop.xhr.abort();
  1126. self.prop.xhr = false;
  1127. }
  1128. };
  1129. /**
  1130. * Suggest result of search keywords
  1131. * @param {Object} self
  1132. */
  1133. SelectPage.prototype.suggest = function (self) {
  1134. var q_word, val = $.trim(self.elem.combo_input.val());
  1135. if (self.option.multiple) q_word = val;
  1136. else {
  1137. if (val && val == self.prop.selected_text) q_word = '';
  1138. else q_word = val;
  1139. }
  1140. q_word = q_word.split(self.option.separator);
  1141. //Before show up result list callback
  1142. if (self.option.eOpen && $.isFunction(self.option.eOpen))
  1143. self.option.eOpen.call(self);
  1144. self.abortAjax(self);
  1145. //self.setLoading(self);
  1146. var which_page_num = self.prop.current_page || 1;
  1147. if (typeof self.option.data == 'object') self.searchForJson(self, q_word, which_page_num);
  1148. else self.searchForDb(self, q_word, which_page_num);
  1149. };
  1150. /**
  1151. * Loading
  1152. * @param {Object} self
  1153. */
  1154. SelectPage.prototype.setLoading = function (self) {
  1155. if (self.elem.results.html() === '') {
  1156. //self.calcResultsSize(self);
  1157. self.setOpenStatus(self, true);
  1158. }
  1159. };
  1160. /**
  1161. * Search for ajax
  1162. * @param {Object} self
  1163. * @param {Array} q_word - query keyword
  1164. * @param {number} which_page_num - target page number
  1165. */
  1166. SelectPage.prototype.searchForDb = function (self, q_word, which_page_num) {
  1167. var p = self.option;
  1168. if (!p.eAjaxSuccess || !$.isFunction(p.eAjaxSuccess)) self.hideResults(self);
  1169. var _paramsFunc = p.params, _params = {}, searchKey = p.searchField;
  1170. //when have new query keyword, then reset page number to 1.
  1171. if (q_word.length && q_word[0] && q_word.join(self.option.separator) !== self.prop.prev_value) which_page_num = 1;
  1172. var _orgParams = {
  1173. q_word: q_word,
  1174. pageNumber: which_page_num,
  1175. pageSize: p.pageSize,
  1176. andOr: p.andOr,
  1177. orderBy: p.orderBy,
  1178. searchTable: p.dbTable,
  1179. showField: self.option.showField,
  1180. keyField: self.option.keyField,
  1181. searchField: self.option.searchField
  1182. };
  1183. if (p.orderBy !== false) _orgParams.orderBy = p.orderBy;
  1184. // 这个应该是历史遗留了,没仔细追逻辑,先留着。
  1185. _orgParams[searchKey] = q_word[0];
  1186. if (_paramsFunc) {
  1187. var result = $.isFunction(_paramsFunc) ? _paramsFunc(self) : _paramsFunc;
  1188. if (result && $.isPlainObject(result)) {
  1189. _params = $.extend({}, _orgParams, result);
  1190. } else {
  1191. _params = _orgParams;
  1192. }
  1193. } else {
  1194. _params = _orgParams;
  1195. }
  1196. self.prop.xhr = $.ajax({
  1197. dataType: 'json',
  1198. url: p.data,
  1199. type: 'POST',
  1200. data: _params,
  1201. success: function (returnData) {
  1202. if (!returnData || !$.isPlainObject(returnData)) {
  1203. self.hideResults(self);
  1204. self.ajaxErrorNotify(self, errorThrown);
  1205. return;
  1206. }
  1207. var data = {}, json = {};
  1208. try {
  1209. data = p.eAjaxSuccess(returnData);
  1210. json.originalResult = data.list;
  1211. json.cnt_whole = data.totalRow;
  1212. } catch (e) {
  1213. self.showMessage(self, self.message.ajax_error);
  1214. return;
  1215. }
  1216. if (self.elem.navi) {
  1217. $(self.elem.navi).toggleClass("hide", json.cnt_whole <= json.originalResult.length);
  1218. }
  1219. json.candidate = [];
  1220. json.keyField = [];
  1221. if (typeof json.originalResult != 'object') {
  1222. self.prop.xhr = null;
  1223. self.notFoundSearch(self);
  1224. return;
  1225. }
  1226. json.cnt_page = json.originalResult.length;
  1227. for (var i = 0; i < json.cnt_page; i++) {
  1228. for (var key in json.originalResult[i]) {
  1229. if (key == p.keyField) {
  1230. json.keyField.push(json.originalResult[i][key]);
  1231. }
  1232. if (key == p.showField) {
  1233. json.candidate.push(json.originalResult[i][key]);
  1234. }
  1235. }
  1236. }
  1237. self.prepareResults(self, json, q_word, which_page_num);
  1238. },
  1239. error: function (jqXHR, textStatus, errorThrown) {
  1240. if (textStatus != 'abort') {
  1241. self.hideResults(self);
  1242. self.ajaxErrorNotify(self, errorThrown);
  1243. }
  1244. },
  1245. complete: function () {
  1246. self.prop.xhr = null;
  1247. }
  1248. });
  1249. };
  1250. /**
  1251. * Search for json data source
  1252. * @param {Object} self
  1253. * @param {Array} q_word
  1254. * @param {number} which_page_num
  1255. */
  1256. SelectPage.prototype.searchForJson = function (self, q_word, which_page_num) {
  1257. var p = self.option, matched = [], esc_q = [], sorted = [], json = {}, i = 0, arr_reg = [];
  1258. //query keyword filter
  1259. do {
  1260. //'/\W/g'正则代表全部不是字母,数字,下划线,汉字的字符
  1261. //将非法字符进行转义
  1262. esc_q[i] = q_word[i].replace(/\W/g, '\\$&').toString();
  1263. arr_reg[i] = new RegExp(esc_q[i], 'gi');
  1264. i++;
  1265. } while (i < q_word.length);
  1266. // SELECT * FROM data WHERE field LIKE q_word;
  1267. for (var i = 0; i < p.data.length; i++) {
  1268. var flag = false, row = p.data[i], itemText;
  1269. for (var j = 0; j < arr_reg.length; j++) {
  1270. itemText = row[p.searchField];
  1271. if (p.formatItem && $.isFunction(p.formatItem))
  1272. itemText = p.formatItem(row);
  1273. if (itemText.match(arr_reg[j])) {
  1274. flag = true;
  1275. if (p.andOr == 'OR') break;
  1276. } else {
  1277. flag = false;
  1278. if (p.andOr == 'AND') break;
  1279. }
  1280. }
  1281. if (flag) matched.push(row);
  1282. }
  1283. // (CASE WHEN ...) then く order some column
  1284. if (p.orderBy === false) sorted = matched.concat();
  1285. else {
  1286. var reg1 = new RegExp('^' + esc_q[0] + '$', 'gi'),
  1287. reg2 = new RegExp('^' + esc_q[0], 'gi'),
  1288. matched1 = [], matched2 = [], matched3 = [];
  1289. for (var i = 0; i < matched.length; i++) {
  1290. var orderField = p.orderBy[0][0];
  1291. var orderValue = String(matched[i][orderField]);
  1292. if (orderValue.match(reg1)) {
  1293. matched1.push(matched[i]);
  1294. } else if (orderValue.match(reg2)) {
  1295. matched2.push(matched[i]);
  1296. } else {
  1297. matched3.push(matched[i]);
  1298. }
  1299. }
  1300. if (p.orderBy[0][1].match(/^asc$/i)) {
  1301. matched1 = self.sortAsc(self, matched1);
  1302. matched2 = self.sortAsc(self, matched2);
  1303. matched3 = self.sortAsc(self, matched3);
  1304. } else {
  1305. matched1 = self.sortDesc(self, matched1);
  1306. matched2 = self.sortDesc(self, matched2);
  1307. matched3 = self.sortDesc(self, matched3);
  1308. }
  1309. sorted = sorted.concat(matched1).concat(matched2).concat(matched3);
  1310. }
  1311. /*
  1312. if (sorted.length === undefined || sorted.length === 0 ) {
  1313. self.notFoundSearch(self);
  1314. return;
  1315. }
  1316. */
  1317. json.cnt_whole = sorted.length;
  1318. //page_move used to distinguish between init plugin or page moving
  1319. if (!self.prop.page_move) {
  1320. //only single mode can be used page number relocation
  1321. if (!p.multiple) {
  1322. //get selected item belong page number
  1323. var currentValue = self.elem.hidden.val();
  1324. if ($.type(currentValue) !== 'undefined' && $.trim(currentValue) !== '') {
  1325. var index = 0;
  1326. $.each(sorted, function (i, row) {
  1327. if (row[p.keyField] == currentValue) {
  1328. index = i + 1;
  1329. return false;
  1330. }
  1331. });
  1332. which_page_num = Math.ceil(index / p.pageSize);
  1333. if (which_page_num < 1) which_page_num = 1;
  1334. self.prop.current_page = which_page_num;
  1335. }
  1336. }
  1337. } else {
  1338. //set page number to 1 when result number less then page size
  1339. if (sorted.length <= ((which_page_num - 1) * p.pageSize)) {
  1340. which_page_num = 1;
  1341. self.prop.current_page = 1;
  1342. }
  1343. }
  1344. //LIMIT xx OFFSET xx
  1345. var start = (which_page_num - 1) * p.pageSize, end = start + p.pageSize;
  1346. //save original data
  1347. json.originalResult = [];
  1348. //after data filter handle
  1349. for (var i = start; i < end; i++) {
  1350. if (sorted[i] === undefined) break;
  1351. json.originalResult.push(sorted[i]);
  1352. for (var key in sorted[i]) {
  1353. if (key == p.keyField) {
  1354. if (json.keyField === undefined) json.keyField = [];
  1355. json.keyField.push(sorted[i][key]);
  1356. }
  1357. if (key == p.showField) {
  1358. if (json.candidate === undefined) json.candidate = [];
  1359. json.candidate.push(sorted[i][key]);
  1360. }
  1361. }
  1362. }
  1363. if (json.candidate === undefined) json.candidate = [];
  1364. json.cnt_page = json.candidate.length;
  1365. self.prepareResults(self, json, q_word, which_page_num);
  1366. };
  1367. /**
  1368. * Set order asc
  1369. * @param {Object} self
  1370. * @param {Array} arr - result array
  1371. */
  1372. SelectPage.prototype.sortAsc = function (self, arr) {
  1373. arr.sort(function (a, b) {
  1374. var valA = a[self.option.orderBy[0][0]], valB = b[self.option.orderBy[0][0]];
  1375. return $.type(valA) === 'number' ? valA - valB : String(valA).localeCompare(String(valB));
  1376. });
  1377. return arr;
  1378. };
  1379. /**
  1380. * Set order desc
  1381. * @param {Object} self
  1382. * @param {Array} arr - result array
  1383. */
  1384. SelectPage.prototype.sortDesc = function (self, arr) {
  1385. arr.sort(function (a, b) {
  1386. var valA = a[self.option.orderBy[0][0]], valB = b[self.option.orderBy[0][0]];
  1387. return $.type(valA) === 'number' ? valB - valA : String(valB).localeCompare(String(valA));
  1388. });
  1389. return arr;
  1390. };
  1391. /**
  1392. * Not result found handle
  1393. * @param {Object} self
  1394. */
  1395. SelectPage.prototype.notFoundSearch = function (self) {
  1396. self.elem.results.empty();
  1397. self.calcResultsSize(self);
  1398. self.setOpenStatus(self, true);
  1399. self.setCssFocusedInput(self);
  1400. };
  1401. /**
  1402. * Prepare data to show
  1403. * @param {Object} self
  1404. * @param {Object} json - data result
  1405. * @param {Array} q_word - query keyword
  1406. * @param {number} which_page_num - target page number
  1407. */
  1408. SelectPage.prototype.prepareResults = function (self, json, q_word, which_page_num) {
  1409. self.data = json.originalResult;
  1410. if (self.option.pagination) self.setNavi(self, json.cnt_whole, json.cnt_page, which_page_num);
  1411. if (!json.keyField) json.keyField = false;
  1412. if (self.option.selectOnly && json.candidate.length === 1 && json.candidate[0] == q_word[0]) {
  1413. self.elem.hidden.val(json.keyField[0]);
  1414. this.setButtonAttrDefault();
  1415. }
  1416. var is_query = false;
  1417. if (q_word && q_word.length && q_word[0]) is_query = true;
  1418. self.displayResults(self, json, is_query);
  1419. };
  1420. /**
  1421. * Build page bar
  1422. * @param {Object} self
  1423. * @param {number} cnt_whole - total record count
  1424. * @param {number} cnt_page
  1425. * @param {number} page_num - current page number
  1426. */
  1427. SelectPage.prototype.setNavi = function (self, cnt_whole, cnt_page, page_num) {
  1428. var msg = self.message;
  1429. /**
  1430. * build pagination bar
  1431. */
  1432. var buildPageNav = function (self, pagebar, page_num, last_page) {
  1433. var updatePageInfo = function () {
  1434. var pageInfo = msg.page_info;
  1435. return pageInfo.replace(self.template.page.current, page_num).replace(self.template.page.total, last_page);
  1436. };
  1437. if (pagebar.find('li').length === 0) {
  1438. pagebar.hide().empty();
  1439. var iconFist = 'spfont sp-first',
  1440. iconPrev = 'spfont sp-previous',
  1441. iconNext = 'spfont sp-next',
  1442. iconLast = 'spfont sp-last';
  1443. pagebar.append('<li class="csFirstPage" title="' + msg.first_title + '" ><a href="javascript:void(0);"> <i class="' + iconFist + '"></i> </a></li>');
  1444. pagebar.append('<li class="csPreviousPage" title="' + msg.prev_title + '" ><a href="javascript:void(0);"><i class="' + iconPrev + '"></i></a></li>');
  1445. //pagination information
  1446. pagebar.append('<li class="pageInfoBox"><a href="javascript:void(0);"> ' + updatePageInfo() + ' </a></li>');
  1447. pagebar.append('<li class="csNextPage" title="' + msg.next_title + '" ><a href="javascript:void(0);"><i class="' + iconNext + '"></i></a></li>');
  1448. pagebar.append('<li class="csLastPage" title="' + msg.last_title + '" ><a href="javascript:void(0);"> <i class="' + iconLast + '"></i> </a></li>');
  1449. pagebar.show();
  1450. } else {
  1451. pagebar.find('li.pageInfoBox a').html(updatePageInfo());
  1452. }
  1453. };
  1454. var pagebar = self.elem.navi.find('ul'),
  1455. last_page = Math.ceil(cnt_whole / self.option.pageSize); //calculate total page
  1456. if (last_page === 0) page_num = 0;
  1457. else {
  1458. if (last_page < page_num) page_num = last_page;
  1459. else if (page_num === 0) page_num = 1;
  1460. }
  1461. self.prop.current_page = page_num;//update current page number
  1462. self.prop.max_page = last_page;//update page count
  1463. buildPageNav(self, pagebar, page_num, last_page);
  1464. //update paging status
  1465. var dClass = 'disabled',
  1466. first = pagebar.find('li.csFirstPage'),
  1467. previous = pagebar.find('li.csPreviousPage'),
  1468. next = pagebar.find('li.csNextPage'),
  1469. last = pagebar.find('li.csLastPage');
  1470. //first and previous
  1471. if (page_num === 1 || page_num === 0) {
  1472. if (!first.hasClass(dClass)) first.addClass(dClass);
  1473. if (!previous.hasClass(dClass)) previous.addClass(dClass);
  1474. } else {
  1475. if (first.hasClass(dClass)) first.removeClass(dClass);
  1476. if (previous.hasClass(dClass)) previous.removeClass(dClass);
  1477. }
  1478. //next and last
  1479. if (page_num === last_page || last_page === 0) {
  1480. if (!next.hasClass(dClass)) next.addClass(dClass);
  1481. if (!last.hasClass(dClass)) last.addClass(dClass);
  1482. } else {
  1483. if (next.hasClass(dClass)) next.removeClass(dClass);
  1484. if (last.hasClass(dClass)) last.removeClass(dClass);
  1485. }
  1486. if (last_page > 1) self.ePaging(); //pagination event bind
  1487. };
  1488. /**
  1489. * Render result list
  1490. * @param {Object} self
  1491. * @param {Object} json - result data
  1492. * @param {boolean} is_query - used to different from search to open and just click to open
  1493. */
  1494. SelectPage.prototype.displayResults = function (self, json, is_query) {
  1495. var p = self.option, el = self.elem;
  1496. el.results.hide().empty();
  1497. if (p.multiple && $.type(p.maxSelectLimit) === 'number' && p.maxSelectLimit > 0) {
  1498. var selectedSize = el.element_box.find('li.selected_tag').length;
  1499. if (selectedSize > 0 && selectedSize >= p.maxSelectLimit) {
  1500. var msg = self.message.max_selected;
  1501. self.showMessage(self, msg.replace(self.template.msg.maxSelectLimit, p.maxSelectLimit));
  1502. return;
  1503. }
  1504. }
  1505. if (json.candidate.length) {
  1506. var arr_candidate = json.candidate,
  1507. arr_primary_key = json.keyField,
  1508. keystr = el.hidden.val(),
  1509. keyArr = keystr ? keystr.split(',') : [],
  1510. itemText = '';
  1511. for (var i = 0; i < arr_candidate.length; i++) {
  1512. if (p.formatItem && $.isFunction(p.formatItem)) {
  1513. try {
  1514. itemText = p.formatItem(json.originalResult[i]);
  1515. } catch (e) {
  1516. console.error('formatItem内容格式化函数内容设置不正确!');
  1517. itemText = p.escape ? self.escapeHTML(arr_candidate[i]) : arr_candidate[i];
  1518. }
  1519. } else {
  1520. itemText = p.escape ? self.escapeHTML(arr_candidate[i]) : arr_candidate[i];
  1521. }
  1522. var list = $('<li>').html(itemText).attr({
  1523. pkey: arr_primary_key[i],
  1524. index: i
  1525. });
  1526. if (!p.formatItem) list.attr('title', itemText);
  1527. //Set selected item highlight
  1528. if ($.inArray(arr_primary_key[i].toString(), keyArr) !== -1) {
  1529. list.addClass(self.css_class.selected);
  1530. }
  1531. //cache item data
  1532. list.data('dataObj', json.originalResult[i]);
  1533. el.results.append(list);
  1534. }
  1535. } else {
  1536. var li = '<li class="' + self.css_class.message_box + '"><i class="spfont sp-warning"></i> ' +
  1537. self.message.not_found + '</li>';
  1538. el.results.append(li);
  1539. }
  1540. el.results.show();
  1541. if (p.multiple && p.multipleControlbar) el.control.show();
  1542. if (p.pagination) el.navi.show();
  1543. self.calcResultsSize(self);
  1544. self.setOpenStatus(self, true);
  1545. //Result item event bind
  1546. self.eResultList();
  1547. //scrolling listen
  1548. self.eScroll();
  1549. //auto highlight first item in search, have result and set autoSelectFirst to true situation
  1550. if (is_query && json.candidate.length && p.autoSelectFirst) self.nextLine(self);
  1551. };
  1552. /**
  1553. * Calculate result list size and position
  1554. * @param {Object} self
  1555. */
  1556. SelectPage.prototype.calcResultsSize = function (self) {
  1557. var p = self.option, el = self.elem;
  1558. var rePosition = function () {
  1559. if (el.container.css('position') === 'static') {
  1560. // position: static
  1561. var offset = el.combo_input.offset();
  1562. el.result_area.css({
  1563. top: offset.top + el.combo_input.outerHeight() + 'px',
  1564. left: offset.left + 'px'
  1565. });
  1566. } else {
  1567. if (!p.pagination) {
  1568. var itemHeight = el.results.find('li:first').outerHeight(true),
  1569. listHeight = itemHeight * p.listSize;
  1570. el.results.css({
  1571. 'max-height': listHeight,
  1572. 'overflow-y': 'auto'
  1573. });
  1574. }
  1575. //handle result list show up side(left, right, up or down)
  1576. var docWidth = $(document).width(),
  1577. docHeight = $(document).height(), //the document full height
  1578. viewHeight = $(window).height(), //browser visible area height
  1579. offset = el.container.offset(),
  1580. screenScrollTop = $(window).scrollTop(),
  1581. listWidth = el.result_area.outerWidth(),
  1582. //result list height
  1583. listHeight = el.result_area.outerHeight(),
  1584. //default left used input element left
  1585. defaultLeft = offset.left, //p.multiple ? -1 : 0;
  1586. //input element height
  1587. inputHeight = el.container.outerHeight(),
  1588. left = (offset.left + listWidth) > docWidth ?
  1589. defaultLeft - (listWidth - el.container.outerWidth()) :
  1590. defaultLeft,
  1591. //the actual top coordinate of input element(outer div)
  1592. screenTop = offset.top, //$(el.container).scrollTop();//offset.top - screenScrollTop;
  1593. top = 0, dist = 5, //set distance between input element and result list
  1594. //the actual top coordinate of result list
  1595. listBottom = screenTop + inputHeight + listHeight + dist,
  1596. listTop = screenTop + listHeight + dist,
  1597. hasOverflow = docHeight > viewHeight;
  1598. if ((screenTop - screenScrollTop - dist > listHeight) &&
  1599. (hasOverflow && listBottom > (viewHeight + screenScrollTop)) ||
  1600. (!hasOverflow && listBottom > viewHeight && screenTop >= listTop)) {
  1601. //open up
  1602. top = offset.top - listHeight - dist;
  1603. el.result_area.removeClass('shadowUp shadowDown').addClass('shadowUp');
  1604. } else {
  1605. //open down
  1606. top = offset.top + (p.multiple ? el.container.outerHeight() : inputHeight);
  1607. el.result_area.removeClass('shadowUp shadowDown').addClass('shadowDown');
  1608. top += dist;
  1609. }
  1610. return {
  1611. top: top + 'px', left: left + 'px'
  1612. };
  1613. }
  1614. };
  1615. if (el.result_area.is(':visible')) {
  1616. el.result_area.css(rePosition());
  1617. } else {
  1618. var pss = rePosition();
  1619. el.result_area.css(pss).show(1, function () {
  1620. var repss = rePosition();
  1621. if (pss.top !== repss.top || pss.left !== repss.left) el.result_area.css(repss);
  1622. });
  1623. }
  1624. };
  1625. /**
  1626. * hide result list
  1627. * @param {Object} self
  1628. */
  1629. SelectPage.prototype.hideResults = function (self) {
  1630. if (self.prop.key_paging) {
  1631. self.scrollWindow(self, true);
  1632. self.prop.key_paging = false;
  1633. }
  1634. self.setCssFocusedInput(self);
  1635. if (self.option.autoFillResult) {
  1636. //self.selectCurrentLine(self, true);
  1637. }
  1638. self.elem.results.empty();
  1639. self.elem.result_area.hide();
  1640. self.setOpenStatus(self, false);
  1641. //unbind window scroll listen
  1642. $(window).off('scroll.SelectPage');
  1643. self.abortAjax(self);
  1644. self.setButtonAttrDefault();
  1645. };
  1646. /**
  1647. * set plugin to disabled / enabled
  1648. * @param self
  1649. * @param disabled
  1650. */
  1651. SelectPage.prototype.disabled = function (self, disabled) {
  1652. var p = self.option, el = self.elem;
  1653. if ($.type(disabled) === 'undefined') return el.combo_input.prop('disabled');
  1654. if ($.type(disabled) === 'boolean') {
  1655. el.combo_input.prop('disabled', disabled);
  1656. if (disabled) el.container.addClass(self.css_class.disabled);
  1657. else el.container.removeClass(self.css_class.disabled);
  1658. }
  1659. };
  1660. /**
  1661. * Go fist page
  1662. * @param {Object} self
  1663. */
  1664. SelectPage.prototype.firstPage = function (self) {
  1665. if (self.prop.current_page > 1) {
  1666. self.prop.current_page = 1;
  1667. self.prop.page_move = true;
  1668. self.suggest(self);
  1669. }
  1670. };
  1671. /**
  1672. * Go previous page
  1673. * @param {Object} self
  1674. */
  1675. SelectPage.prototype.prevPage = function (self) {
  1676. if (self.prop.current_page > 1) {
  1677. self.prop.current_page--;
  1678. self.prop.page_move = true;
  1679. self.suggest(self);
  1680. }
  1681. };
  1682. /**
  1683. * Go next page
  1684. * @param {Object} self
  1685. */
  1686. SelectPage.prototype.nextPage = function (self) {
  1687. if (self.prop.current_page < self.prop.max_page) {
  1688. self.prop.current_page++;
  1689. self.prop.page_move = true;
  1690. self.suggest(self);
  1691. }
  1692. };
  1693. /**
  1694. * Go last page
  1695. * @param {Object} self
  1696. */
  1697. SelectPage.prototype.lastPage = function (self) {
  1698. if (self.prop.current_page < self.prop.max_page) {
  1699. self.prop.current_page = self.prop.max_page;
  1700. self.prop.page_move = true;
  1701. self.suggest(self);
  1702. }
  1703. };
  1704. /**
  1705. * do something after select/unSelect action
  1706. * @param {Object} self
  1707. * @param {boolean} reOpen
  1708. */
  1709. SelectPage.prototype.afterAction = function (self, reOpen) {
  1710. self.inputResize(self);
  1711. self.elem.combo_input.change();
  1712. self.setCssFocusedInput(self);
  1713. if (self.prop.init_set) return;
  1714. if (self.option.multiple) {
  1715. if (self.option.selectToCloseList) {
  1716. self.hideResults(self);
  1717. self.elem.combo_input.blur();
  1718. }
  1719. if (!self.option.selectToCloseList && reOpen) {
  1720. self.suggest(self);
  1721. self.elem.combo_input.focus();
  1722. }
  1723. } else {
  1724. self.hideResults(self);
  1725. self.elem.combo_input.blur();
  1726. }
  1727. };
  1728. /**
  1729. * Select current list item
  1730. * @param {Object} self
  1731. * @param {boolean} is_enter_key
  1732. */
  1733. SelectPage.prototype.selectCurrentLine = function (self, is_enter_key) {
  1734. self.scrollWindow(self, true);
  1735. var p = self.option, current = self.getCurrentLine(self);
  1736. if (current) {
  1737. var data = current.data('dataObj');
  1738. var text = data[p.showField] || current.text();
  1739. var value = current.attr('pkey');
  1740. if (!p.multiple) {
  1741. self.elem.combo_input.val(text);
  1742. self.elem.hidden.val(value);
  1743. } else {
  1744. //build tags in multiple selection mode
  1745. self.elem.combo_input.val('');
  1746. var item = {text: text, value: value};
  1747. if (!self.isAlreadySelected(self, item)) {
  1748. self.addNewTag(self, data, item);
  1749. self.tagValuesSet(self);
  1750. }
  1751. }
  1752. if (p.selectOnly) self.setButtonAttrDefault();
  1753. //Select item callback
  1754. if (p.eSelect && $.isFunction(p.eSelect)) p.eSelect(data, self);
  1755. self.prop.prev_value = self.elem.combo_input.val();
  1756. self.prop.selected_text = self.elem.combo_input.val();
  1757. self.putClearButton();
  1758. }
  1759. self.afterAction(self, true);
  1760. };
  1761. /**
  1762. * Show clear button when item selected in single selection mode
  1763. */
  1764. SelectPage.prototype.putClearButton = function () {
  1765. if (!this.option.multiple && !this.elem.combo_input.prop('disabled')) this.elem.container.append(this.elem.clear_btn);
  1766. };
  1767. /**
  1768. * Select all list item
  1769. * @param {Object} self
  1770. */
  1771. SelectPage.prototype.selectAllLine = function (self) {
  1772. var p = self.option, jsonarr = new Array();
  1773. self.elem.results.find('li').each(function (i, row) {
  1774. var $row = $(row), data = $row.data('dataObj');
  1775. var text = data[p.showField] || $row.text();
  1776. var value = $row.attr('pkey');
  1777. var item = {text: text, value: value};
  1778. if (!self.isAlreadySelected(self, item)) {
  1779. self.addNewTag(self, data, item);
  1780. self.tagValuesSet(self);
  1781. }
  1782. jsonarr.push(data);
  1783. //limited max selected items
  1784. if ($.type(p.maxSelectLimit) === 'number' &&
  1785. p.maxSelectLimit > 0 &&
  1786. p.maxSelectLimit === self.elem.element_box.find('li.selected_tag').length) {
  1787. return false;
  1788. }
  1789. });
  1790. if (p.eSelect && $.isFunction(p.eSelect)) p.eSelect(jsonarr, self);
  1791. self.afterAction(self, true);
  1792. };
  1793. /**
  1794. * Cancel select all item in current page
  1795. * @param {Object} self
  1796. */
  1797. SelectPage.prototype.unSelectAllLine = function (self) {
  1798. var p = self.option, size = self.elem.results.find('li').length, ds = [];
  1799. self.elem.results.find('li').each(function (i, row) {
  1800. var key = $(row).attr('pkey');
  1801. var tag = self.elem.element_box.find('li.selected_tag[itemvalue="' + key + '"]');
  1802. if (tag.length) ds.push(tag.data('dataObj'));
  1803. self.removeTag(self, tag);
  1804. });
  1805. self.afterAction(self, true);
  1806. if (p.eTagRemove && $.isFunction(p.eTagRemove)) p.eTagRemove(ds);
  1807. };
  1808. /**
  1809. * Clear all selected items
  1810. * @param {Object} self
  1811. * @param {boolean} open - open list after clear selected item
  1812. */
  1813. SelectPage.prototype.clearAll = function (self, open) {
  1814. var p = self.option, ds = [];
  1815. if (p.multiple) {
  1816. self.elem.element_box.find('li.selected_tag').each(function (i, row) {
  1817. ds.push($(row).data('dataObj'));
  1818. row.remove();
  1819. });
  1820. self.elem.element_box.find('li.selected_tag').remove();
  1821. }
  1822. self.reset(self);
  1823. self.afterAction(self, open);
  1824. if (p.multiple) {
  1825. if (p.eTagRemove && $.isFunction(p.eTagRemove)) p.eTagRemove(ds);
  1826. } else self.elem.clear_btn.remove();
  1827. };
  1828. /**
  1829. * reset
  1830. */
  1831. SelectPage.prototype.reset = function (self) {
  1832. self.elem.combo_input.val('');
  1833. self.elem.hidden.val('');
  1834. self.prop.prev_value = '';
  1835. self.prop.selected_text = '';
  1836. self.prop.current_page = 1;
  1837. };
  1838. /**
  1839. * Get current highlight item
  1840. * @param {Object} self
  1841. */
  1842. SelectPage.prototype.getCurrentLine = function (self) {
  1843. if (self.elem.result_area.is(':hidden')) return false;
  1844. var obj = self.elem.results.find('li.' + self.css_class.select);
  1845. if (obj.length) return obj;
  1846. else return false;
  1847. };
  1848. /**
  1849. * Check the result item is already selected or not
  1850. * @param {Object} self
  1851. * @param {Object} item - item info
  1852. */
  1853. SelectPage.prototype.isAlreadySelected = function (self, item) {
  1854. var isExist = false;
  1855. if (item.value) {
  1856. var keys = self.elem.hidden.val();
  1857. if (keys) {
  1858. var karr = keys.split(',');
  1859. if (karr && karr.length && $.inArray(item.value, karr) != -1) isExist = true;
  1860. }
  1861. }
  1862. return isExist;
  1863. };
  1864. /**
  1865. * Add a new tag in multiple selection mode
  1866. * @param {Object} self
  1867. * @param {object} data - raw row data
  1868. * @param {Object} item
  1869. */
  1870. SelectPage.prototype.addNewTag = function (self, data, item) {
  1871. if (!self.option.multiple || !data || !item) return;
  1872. var tmp = self.template.tag.content, tag;
  1873. tmp = tmp.replace(self.template.tag.textKey, item.text);
  1874. tmp = tmp.replace(self.template.tag.valueKey, item.value);
  1875. tag = $(tmp);
  1876. tag.data('dataObj', data);
  1877. if (self.elem.combo_input.prop('disabled')) tag.find('span.tag_close').hide();
  1878. self.elem.combo_input.closest('li').before(tag);
  1879. };
  1880. /**
  1881. * Remove a tag in multiple selection mode
  1882. * @param {Object} self
  1883. * @param {Object} item
  1884. */
  1885. SelectPage.prototype.removeTag = function (self, item) {
  1886. var key = $(item).attr('itemvalue');
  1887. var keys = self.elem.hidden.val();
  1888. if ($.type(key) != 'undefined' && keys) {
  1889. var keyarr = keys.split(','),
  1890. index = $.inArray(key.toString(), keyarr);
  1891. if (index != -1) {
  1892. keyarr.splice(index, 1);
  1893. self.elem.hidden.val(keyarr.toString()).trigger("change");
  1894. }
  1895. }
  1896. $(item).remove();
  1897. self.inputResize(self);
  1898. };
  1899. /**
  1900. * Selected item value(keyField) put in to hidden element
  1901. * @param {Object} self
  1902. */
  1903. SelectPage.prototype.tagValuesSet = function (self) {
  1904. if (!self.option.multiple) return;
  1905. var tags = self.elem.element_box.find('li.selected_tag');
  1906. if (tags && tags.length) {
  1907. var result = new Array();
  1908. $.each(tags, function (i, li) {
  1909. var v = $(li).attr('itemvalue');
  1910. if ($.type(v) !== 'undefined') result.push(v);
  1911. });
  1912. if (result.length) {
  1913. self.elem.hidden.val(result.join(',')).trigger("change");
  1914. }
  1915. }
  1916. };
  1917. /**
  1918. * auto resize input element width in multiple select mode
  1919. * @param {Object} self
  1920. */
  1921. SelectPage.prototype.inputResize = function (self) {
  1922. if (!self.option.multiple) return;
  1923. var width = '',
  1924. inputLi = self.elem.combo_input.closest('li');
  1925. var setDefaultSize = function (self, inputLi) {
  1926. inputLi.removeClass('full_width');
  1927. var minimumWidth = self.elem.combo_input.val().length + 1,
  1928. width = (minimumWidth * 0.75) + 'em';
  1929. self.elem.combo_input.css('width', width).removeAttr('placeholder');
  1930. };
  1931. if (self.elem.element_box.find('li.selected_tag').length === 0) {
  1932. if (!inputLi.hasClass('full_width')) inputLi.addClass('full_width');
  1933. if (self.elem.combo_input.attr('placeholder_bak')) {
  1934. self.elem.combo_input.attr('placeholder', self.elem.combo_input.attr('placeholder_bak')).removeAttr('style');
  1935. }
  1936. } else setDefaultSize(self, inputLi);
  1937. };
  1938. /**
  1939. * Move to next line
  1940. * @param {Object} self
  1941. */
  1942. SelectPage.prototype.nextLine = function (self) {
  1943. var obj = self.getCurrentLine(self), idx;
  1944. if (!obj) idx = -1;
  1945. else {
  1946. idx = self.elem.results.children('li').index(obj);
  1947. obj.removeClass(self.css_class.select);
  1948. }
  1949. idx++;
  1950. if (idx < self.elem.results.children('li').length) {
  1951. var next = self.elem.results.children('li').eq(idx);
  1952. next.addClass(self.css_class.select);
  1953. self.setCssFocusedResults(self);
  1954. } else self.setCssFocusedInput(self);
  1955. self.scrollWindow(self, false);
  1956. };
  1957. /**
  1958. * Move to previous line
  1959. * @param {Object} self
  1960. */
  1961. SelectPage.prototype.prevLine = function (self) {
  1962. var obj = self.getCurrentLine(self), idx;
  1963. if (!obj) idx = self.elem.results.children('li').length;
  1964. else {
  1965. idx = self.elem.results.children('li').index(obj);
  1966. obj.removeClass(self.css_class.select);
  1967. }
  1968. idx--;
  1969. if (idx > -1) {
  1970. var prev = self.elem.results.children('li').eq(idx);
  1971. prev.addClass(self.css_class.select);
  1972. self.setCssFocusedResults(self);
  1973. } else self.setCssFocusedInput(self);
  1974. self.scrollWindow(self, false);
  1975. };
  1976. /**
  1977. * SelectPage plugin definition
  1978. * @global
  1979. * @param option {Object} init plugin option
  1980. */
  1981. function Plugin(option) {
  1982. return this.each(function () {
  1983. var $this = $(this),
  1984. data = $this.data(SelectPage.dataKey),
  1985. params = $.extend({}, defaults, $this.data(), data && data.option, typeof option === 'object' && option);
  1986. if (!data) $this.data(SelectPage.dataKey, (data = new SelectPage(this, params)));
  1987. });
  1988. }
  1989. /**
  1990. * Get plugin object
  1991. * @param {object} obj
  1992. * @returns
  1993. */
  1994. function getPlugin(obj) {
  1995. return $(obj).closest('div.sp_container').find('input.sp_input');
  1996. }
  1997. /**
  1998. * Clear all selected item
  1999. */
  2000. function ClearSelected() {
  2001. return this.each(function () {
  2002. var $this = getPlugin(this),
  2003. data = $this.data(SelectPage.dataKey);
  2004. if (data) {
  2005. data.prop.init_set = true;
  2006. data.clearAll(data);
  2007. data.prop.init_set = false;
  2008. }
  2009. });
  2010. }
  2011. /**
  2012. * Refresh result list
  2013. * use case:
  2014. * 1.use $(obj).val('xxx') to modify selectpage selected item key
  2015. * 2.refresh selected item show content/tag text
  2016. */
  2017. function SelectedRefresh() {
  2018. return this.each(function () {
  2019. var $this = getPlugin(this),
  2020. data = $this.data(SelectPage.dataKey);
  2021. if (data && data.elem.hidden.val())
  2022. data.setInitRecord(true);
  2023. });
  2024. }
  2025. /**
  2026. * Modify plugin datasource, only work on json datasource mode
  2027. * @param {array} data - new datasource
  2028. * @example
  2029. * [{name:'aa',sex:1},{name:'bb',sex:0},{...}]
  2030. */
  2031. function ModifyDataSource(data) {
  2032. return this.each(function () {
  2033. if (data && $.isArray(data)) {
  2034. var $this = getPlugin(this),
  2035. plugin = $this.data(SelectPage.dataKey);
  2036. if (plugin) {
  2037. plugin.clearAll(plugin);
  2038. plugin.option.data = data;
  2039. }
  2040. }
  2041. });
  2042. }
  2043. /**
  2044. * Get plugin disabled status or Modify plugin disabled status
  2045. * @param disabled {boolean} set disabled status
  2046. */
  2047. function PluginDisabled(disabled) {
  2048. var status = false;
  2049. this.each(function () {
  2050. var $this = getPlugin(this),
  2051. plugin = $this.data(SelectPage.dataKey);
  2052. if (plugin) {
  2053. if ($.type(disabled) !== 'undefined')
  2054. plugin.disabled(plugin, disabled);
  2055. else
  2056. status = plugin.disabled(plugin);
  2057. }
  2058. });
  2059. return status;
  2060. }
  2061. /**
  2062. * Get selected item text
  2063. * @returns {string}
  2064. */
  2065. function GetInputText() {
  2066. var str = '';
  2067. this.each(function () {
  2068. var $this = getPlugin(this), data = $this.data(SelectPage.dataKey);
  2069. if (data) {
  2070. if (data.option.multiple) {
  2071. var tags = [];
  2072. data.elem.element_box.find('li.selected_tag').each(function (i, tag) {
  2073. tags.push($(tag).text());
  2074. });
  2075. str += tags.toString();
  2076. } else {
  2077. str += data.elem.combo_input.val();
  2078. }
  2079. }
  2080. });
  2081. return str;
  2082. }
  2083. /**
  2084. * Get selected item raw data
  2085. * @returns {any[]}
  2086. */
  2087. function GetSelectedData() {
  2088. var results = [];
  2089. this.each(function () {
  2090. var $this = getPlugin(this), data = $this.data(SelectPage.dataKey);
  2091. if (data) {
  2092. if (data.option.multiple) {
  2093. data.elem.element_box.find('li.selected_tag').each(function (i, tag) {
  2094. results.push($(tag).data('dataObj'));
  2095. });
  2096. } else {
  2097. var selected = data.elem.combo_input.data('dataObj');
  2098. if (selected) results.push(selected);
  2099. }
  2100. }
  2101. });
  2102. return results;
  2103. }
  2104. var old = $.fn.selectPage;
  2105. $.fn.selectPage = Plugin;
  2106. $.fn.selectPage.Constructor = SelectPage;
  2107. $.fn.selectPageClear = ClearSelected;
  2108. $.fn.selectPageRefresh = SelectedRefresh;
  2109. $.fn.selectPageData = ModifyDataSource;
  2110. $.fn.selectPageDisabled = PluginDisabled;
  2111. $.fn.selectPageText = GetInputText;
  2112. $.fn.selectPageSelectedData = GetSelectedData;
  2113. // SelectPage no conflict
  2114. // =================
  2115. $.fn.selectPage.noConflict = function () {
  2116. $.fn.selectPage = old;
  2117. return this;
  2118. };
  2119. })(window.jQuery);