selectpage.js 80 KB

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