selectpage.js 80 KB

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