当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
1 Star 0 Fork 50

sloth4413/SelectPage
暂停

forked from TerryZ/SelectPage
暂停
 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
selectpage.min.js 39.34 KB
一键复制 编辑 原始数据 按行查看 历史
;(function($){"use strict";var defaults={data:undefined,lang:'cn',multiple:false,multipleControlbar:true,maxSelectLimit:0,selectToCloseList:true,initRecord:undefined,dbTable:'tbl',primaryKey:'id',field:'name',searchField:undefined,andOr:'AND',pageSize:10,params:undefined,formatItem:undefined,focusDropList:true,autoSelectFirst:true,autoFillResult:true,noResultClean:true,selectOnly:false,eSelect:undefined,eAjaxSuccess:undefined,eTagRemove:undefined};var SelectPage=function(input,option){this.setOption(option);this.setLanguage();this.setCssClass();this.setProp();this.setElem(input,option);this.setButtonAttrDefault();this.setInitRecord();this.eDropdownButton();this.eInput();this.eWhole();};SelectPage.version='2.0';SelectPage.dataKey='selectPageObject';SelectPage.objStatusKey='selectPage-self-mark';SelectPage.objStatusIndex='selectPage-self-index';SelectPage.prototype.setOption=function(option){option.searchField=(option.searchField===undefined)?option.field:option.searchField;option.andOr=option.andOr.toUpperCase();var arr=['searchField'];for(var i=0;i<arr.length;i++){option[arr[i]]=this.strToArray(option[arr[i]]);}option.orderBy=(option.orderBy===undefined)?option.searchField:option.orderBy;option.orderBy=this.setOrderbyOption(option.orderBy,option.field);if(option.multiple&&!option.selectToCloseList){option.autoFillResult=false;option.autoSelectFirst=false;}if($.type(option.init)!='undefined')option.initRecord=String(option.init);this.option=option;};SelectPage.prototype.strToArray=function(str){if(!str)return'';return str.replace(/[\s ]+/g,'').split(',');};SelectPage.prototype.setOrderbyOption=function(arg_order,arg_field){var arr=[],orders=[];if(typeof arg_order=='object'){for(var i=0;i<arg_order.length;i++){orders=$.trim(arg_order[i]).split(' ');arr[i]=(orders.length==2)?orders:[orders[0],'ASC'];}}else{orders=$.trim(arg_order).split(' ');arr[0]=(orders.length==2)?orders:(orders[0].match(/^(ASC|DESC)$/i))?[arg_field,orders[0]]:[orders[0],'ASC'];}return arr;};SelectPage.prototype.setLanguage=function(){var message;switch(this.option.lang){case'de':message={add_btn:'Hinzufügen-Button',add_title:'Box hinzufügen',del_btn:'Löschen-Button',del_title:'Box löschen',next:'Nächsten',next_title:'Nächsten'+this.option.pageSize+' (Pfeil-rechts)',prev:'Vorherigen',prev_title:'Vorherigen'+this.option.pageSize+' (Pfeil-links)',first_title:'Ersten (Umschalt + Pfeil-links)',last_title:'Letzten (Umschalt + Pfeil-rechts)',get_all_btn:'alle (Pfeil-runter)',get_all_alt:'(Button)',close_btn:'Schließen (Tab)',close_alt:'(Button)',loading:'lade...',loading_alt:'(lade)',page_info:'num_page_top - num_page_end von cnt_whole',select_ng:'Achtung: Bitte wählen Sie aus der Liste aus.',select_ok:'OK : Richtig ausgewählt.',not_found:'nicht gefunden',ajax_error:'Bei der Verbindung zum Server ist ein Fehler aufgetreten. (ajax-combobox)'};break;case'en':message={add_btn:'Add button',add_title:'add a box',del_btn:'Del button',del_title:'delete a box',next:'Next',next_title:'Next'+this.option.pageSize+' (Right key)',prev:'Prev',prev_title:'Prev'+this.option.pageSize+' (Left key)',first_title:'First (Shift + Left key)',last_title:'Last (Shift + Right key)',get_all_btn:'Get All (Down key)',get_all_alt:'(button)',close_btn:'Close (Tab key)',close_alt:'(button)',loading:'loading...',loading_alt:'(loading)',page_info:'num_page_top - num_page_end of cnt_whole',select_ng:'Attention : Please choose from among the list.',select_ok:'OK : Correctly selected.',not_found:'not found',ajax_error:'An error occurred while connecting to server. (ajax-combobox)'};break;case'cn':message={add_btn:'添加按钮',add_title:'添加区域',del_btn:'删除按钮',del_title:'删除区域',next:'下一页',next_title:''+this.option.pageSize+' (→)',prev:'上一页',prev_title:''+this.option.pageSize+' (←)',first_title:'首页 (Shift + ←)',last_title:'尾页 (Shift + →)',get_all_btn:'获得全部 (↓)',get_all_alt:'(按钮)',close_btn:'关闭 (Tab键)',close_alt:'(按钮)',loading:'读取中...',loading_alt:'(读取中)',page_info:'num_page_top - num_page_end (共 cnt_whole)',select_ng:'请注意:请从列表中选择.',select_ok:'OK : 已经选择.',not_found:'无查询结果',ajax_error:'连接到服务器时发生错误!'};break;case'es':message={add_btn:'Agregar boton',add_title:'Agregar una opcion',del_btn:'Borrar boton',del_title:'Borrar una opcion',next:'Siguiente',next_title:'Proximas '+this.option.pageSize+' (tecla derecha)',prev:'Anterior',prev_title:'Anteriores '+this.option.pageSize+' (tecla izquierda)',first_title:'Primera (Shift + Left)',last_title:'Ultima (Shift + Right)',get_all_btn:'Ver todos (tecla abajo)',get_all_alt:'(boton)',close_btn:'Cerrar (tecla TAB)',close_alt:'(boton)',loading:'Cargando...',loading_alt:'(Cargando)',page_info:'num_page_top - num_page_end de cnt_whole',select_ng:'Atencion: Elija una opcion de la lista.',select_ok:'OK: Correctamente seleccionado.',not_found:'no encuentre',ajax_error:'Un error ocurrió mientras conectando al servidor. (ajax-combobox)'};break;case'pt-br':message={add_btn:'Adicionar botão',add_title:'Adicionar uma caixa',del_btn:'Apagar botão',del_title:'Apagar uma caixa',next:'Próxima',next_title:'Próxima '+this.option.pageSize+' (tecla direita)',prev:'Anterior',prev_title:'Anterior '+this.option.pageSize+' (tecla esquerda)',first_title:'Primeira (Shift + Left)',last_title:'Última (Shift + Right)',get_all_btn:'Ver todos (Seta para baixo)',get_all_alt:'(botão)',close_btn:'Fechar (tecla TAB)',close_alt:'(botão)',loading:'Carregando...',loading_alt:'(Carregando)',page_info:'num_page_top - num_page_end de cnt_whole',select_ng:'Atenção: Escolha uma opção da lista.',select_ok:'OK: Selecionado Corretamente.',not_found:'não encontrado',ajax_error:'Um erro aconteceu enquanto conectando a servidor. (ajax-combobox)'};break;case'ja':message={add_btn:'追加ボタン',add_title:'入力ボックスを追加します',del_btn:'削除ボタン',del_title:'入力ボックスを削除します',next:'次へ',next_title:'次の'+this.option.pageSize+'件 (右キー)',prev:'前へ',prev_title:'前の'+this.option.pageSize+'件 (左キー)',first_title:'最初のページへ (Shift + 左キー)',last_title:'最後のページへ (Shift + 右キー)',get_all_btn:'全件取得 (下キー)',get_all_alt:'画像:ボタン',close_btn:'閉じる (Tabキー)',close_alt:'画像:ボタン',loading:'読み込み中...',loading_alt:'画像:読み込み中...',page_info:'num_page_top - num_page_end 件 (全 cnt_whole 件)',select_ng:'注意 : リストの中から選択してください',select_ok:'OK : 正しく選択されました。',not_found:'(0 件)',ajax_error:'サーバとの通信でエラーが発生しました。(ajax-combobox)'};break;}this.message=message;};SelectPage.prototype.setCssClass=function(){var css_class={container:'sp_container',container_open:'sp_container_open',selected:'sp_selected',re_area:'sp_result_area',control_box:'sp_control_box',element_box:'sp_element_box',navi:'sp_navi',results:'sp_results',re_off:'sp_results_off',select:'sp_over',select_ok:'sp_select_ok',select_ng:'sp_select_ng',input_off:'sp_input_off',message_box:'sp_message_box',button:'sp_button',btn_on:'sp_btn_on',btn_out:'sp_btn_out',input:'sp_input'};this.css_class=css_class;};SelectPage.prototype.setProp=function(){this.prop={is_suggest:false,page_all:1,page_suggest:1,max_all:1,max_suggest:1,is_paging:false,is_loading:false,xhr:false,key_paging:false,key_select:false,prev_value:''};this.template={tag:{content:'<li class="selected_tag" itemvalue="#item_value#">#item_text#<span class="tag_close">x</span></li>',textKey:'#item_text#',valueKey:'#item_value#'}};};SelectPage.prototype.setElem=function(combo_input,option){var elem={};var orgWidth=$(combo_input).outerWidth();elem.combo_input=$(combo_input).attr({'autocomplete':'off'}).addClass(this.css_class.input).wrap('<div>');elem.container=$(elem.combo_input).parent().addClass(this.css_class.container);$(elem.container).width(orgWidth);elem.button=$('<div>').addClass(this.css_class.button);elem.dropdown=$('<span class="bs-caret"><span class="caret"></span></span>');elem.element_box=$('<ul>').addClass(this.css_class.element_box);if(option.multiple&&option.multipleControlbar)elem.control=$('<div>').addClass(this.css_class.control_box);elem.result_area=$('<div>').addClass(this.css_class.re_area);elem.navi=$('<div>').addClass('pagination').append('<ul>');elem.results=$('<ul>').addClass(this.css_class.results);var namePrefix='_text';var input_id=($(elem.combo_input).attr('id')!==undefined)?$(elem.combo_input).attr('id'):$(elem.combo_input).attr('name');var input_name=($(elem.combo_input).attr('name')!==undefined)?$(elem.combo_input).attr('name'):'selectPage';var hidden_name=input_name,hidden_id=input_id;if(input_name.match(/\]$/))input_name=input_name.replace(/\]?$/,namePrefix);else input_name+=namePrefix;if(input_id.match(/\]$/))input_id=input_id.replace(/\]?$/,namePrefix);else input_id+=namePrefix;elem.hidden=$('<input type="hidden" class="sp_hidden" />').attr({name:hidden_name,id:hidden_id}).val('');$(elem.combo_input).attr({name:input_name,id:input_id});$(elem.container).append(elem.button).append(elem.result_area).append(elem.hidden);$(elem.button).append(elem.dropdown);$(elem.result_area).append(elem.results).append(elem.navi);if(option.multiple){if(option.multipleControlbar){$(elem.control).append('<button type="button" class="btn btn-default sp_select_all" ><i class="fa fa-check-square-o"></i> 全选本页</button>');$(elem.control).append('<button type="button" class="btn btn-default sp_unselect_all" ><i class="fa fa-square-o"></i> 取消本页</button>');$(elem.control).append('<button type="button" class="btn btn-default sp_clear_all" ><i class="fa fa-ban"></i> 清除全部</button>');$(elem.result_area).prepend(elem.control);}$(elem.container).addClass('sp_container_combo');$(elem.combo_input).addClass('sp_combo_input').before($(elem.element_box));var li=$('<li>').addClass('input_box');$(li).append($(elem.combo_input));$(elem.element_box).append($(li));if($(elem.combo_input).attr('placeholder'))$(elem.combo_input).attr('placeholder_bak',$(elem.combo_input).attr('placeholder'));}this.elem=elem;};SelectPage.prototype.setButtonAttrDefault=function(){if(this.option.selectOnly){if($(this.elem.combo_input).val()!==''){if($(this.elem.hidden).val()!==''){$(this.elem.combo_input).attr('title',this.message.select_ok).removeClass(this.css_class.select_ng).addClass(this.css_class.select_ok);}else{$(this.elem.combo_input).attr('title',this.message.select_ng).removeClass(this.css_class.select_ok).addClass(this.css_class.select_ng);}}else{$(this.elem.hidden).val('');$(this.elem.combo_input).removeAttr('title').removeClass(this.css_class.select_ng);}}$(this.elem.button).attr('title',this.message.get_all_btn);$(this.elem.button).attr('title',this.message.close_btn);};SelectPage.prototype.setInitRecord=function(refresh){var self=this;if((refresh&&$(self.elem.hidden).val())||$.type(self.option.initRecord)=='string'){if(!refresh)$(self.elem.hidden).val(self.option.initRecord);if(typeof self.option.data=='object'){var data=new Array();var keyarr=refresh?$(self.elem.hidden).val().split(','):self.option.initRecord.split(',');$.each(keyarr,function(index,row){for(var i=0;i<self.option.data.length;i++){if(self.option.data[i][self.option.primaryKey]==row){data.push(self.option.data[i]);break;}}});if(!self.option.multiple&&data.length>1)data=null;self.afterInit(self,data);}else{$.ajax({dataType:'json',url:self.option.data,data:{db_table:self.option.dbTable,pkey_name:self.option.primaryKey,pkey_val:self.option.initRecord},success:function(json){self.afterInit(self,json);},error:function(jqXHR,textStatus,errorThrown){self.ajaxErrorNotify(self,errorThrown);}});}}};SelectPage.prototype.afterInit=function(self,data){if(!data)return;if(!$.isArray(data))data=[data];if(self.option.multiple){$(self.elem.combo_input).val('');$.each(data,function(i,row){var item={text:row[self.option.field],value:row[self.option.primaryKey]};if(!self.isAlreadySelected(self,item))self.addNewTag(self,item);});self.tagValuesSet(self);self.inputResize(self);}else{var row=data[0];$(self.elem.combo_input).val(row[self.option.field]);$(self.elem.hidden).val(row[self.option.primaryKey]);self.prop.prev_value=row[self.option.field];if(self.option.selectOnly){$(self.elem.combo_input).attr('title',self.message.select_ok).removeClass(self.css_class.select_ng).addClass(self.css_class.select_ok);}}};SelectPage.prototype.eDropdownButton=function(){var self=this;$(self.elem.button).mouseup(function(ev){if($(self.elem.result_area).is(':hidden')&&!$(self.elem.combo_input).prop('disabled')){$(self.elem.combo_input).focus();}else{self.hideResults(self);}ev.stopPropagation();}).mouseover(function(){$(self.elem.button).addClass(self.css_class.btn_on).removeClass(self.css_class.btn_out);}).mouseout(function(){$(self.elem.button).addClass(self.css_class.btn_out).removeClass(self.css_class.btn_on);}).mouseout();};SelectPage.prototype.eInput=function(){var self=this;var showList=function(){self.prop.page_move=false;self.prop.is_suggest=false;self.suggest(self);self.setCssFocusedInput(self);};$(self.elem.combo_input).keyup(function(ev){self.processKey(self,ev);}).focus(function(e){if($(self.elem.result_area).is(':hidden')){e.stopPropagation();self.prop.first_show=true;showList();}});if(self.option.multiple){if(self.option.multipleControlbar){$('.sp_select_all',self.elem.control).on('click.SelectPage',function(e){self.selectAllLine(self);});$('.sp_unselect_all',self.elem.control).on('click.SelectPage',function(e){self.unselectAllLine(self);});$('.sp_clear_all',self.elem.control).on('click.SelectPage',function(e){self.clearAll(self);});}$(self.elem.element_box).on('click.SelectPage',function(e){var srcEl=e.target||e.srcElement;if($(srcEl).is('ul'))$(self.elem.combo_input).focus();});$(self.elem.element_box).on('click.SelectPage','span.tag_close',function(){var li=$(this).closest('li');self.removeTag(self,li);showList();if(self.option.eAjaxSuccess&&$.isFunction(self.option.eAjaxSuccess))self.option.eAjaxSuccess(1);});self.inputResize(self);}};SelectPage.prototype.eWhole=function(){var self=this;$(self.elem.container).mousedown(function(){var thisindex=$('div.sp_container').index(this);var lastindex=$(document.body).data(SelectPage.objStatusIndex);if(lastindex!=undefined&&thisindex!=lastindex){$(document.body).data(SelectPage.objStatusKey,false);}else{$(document.body).data(SelectPage.objStatusKey,true);}$(document.body).data(SelectPage.objStatusIndex,thisindex);});$(document).off('mousedown.selectPage').on('mousedown.selectPage',function(e){if($(document.body).data(SelectPage.objStatusKey))$(document.body).data(SelectPage.objStatusKey,false);else{var cleanContent=function(obj){$(obj.elem.combo_input).val('');if(!obj.option.multiple)$(obj.elem.hidden).val('');};$('div.'+self.css_class.container+'.'+self.css_class.container_open).each(function(){var d=$('input.'+self.css_class.input,this).data(SelectPage.dataKey);if(!$(d.elem.combo_input).val()&&$(d.elem.hidden).val()&&!d.option.multiple){d.prop.page_all=1;cleanContent(d);d.hideResults(d);return true;}if($('li',$(d.elem.results)).size()>0){if(d.option.autoFillResult){if($('li.sp_selected',$(d.elem.results)).size()>0){d.hideResults(d);}else if($('li.sp_over',$(d.elem.results)).size()>0){if($(d.elem.hidden).val())d.hideResults(d);else d.selectCurrentLine(d,true);}else if(d.option.autoSelectFirst){if($(d.elem.hidden).val())d.hideResults(d);else{d.nextLine(d);d.selectCurrentLine(d,true);}}else{d.hideResults(d);}}else d.hideResults(d);}else{if(d.option.noResultClean)cleanContent(d);else{if(!d.option.multiple)$(d.elem.hidden).val('');}d.hideResults(d);}});}});};SelectPage.prototype.eResultList=function(){var self=this;$(self.elem.results).children('li').mouseover(function(){if(self.prop.key_select){self.prop.key_select=false;return;}$(self.elem.results).children('li').removeClass(self.css_class.select);$(this).addClass(self.css_class.select);self.setCssFocusedResults(self);}).click(function(e){if(self.prop.key_select){self.prop.key_select=false;return;}e.preventDefault();e.stopPropagation();self.selectCurrentLine(self,false);});};SelectPage.prototype.ehNaviPaging=function(){var self=this;$('li.csFirstPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self.firstPage(self);});$('li.csPreviousPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self.prevPage(self);});$('li.csNextPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self.nextPage(self);});$('li.csLastPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self.lastPage(self);});};SelectPage.prototype.ajaxErrorNotify=function(self,errorThrown){self.showMessage(self.message.ajax_error);};SelectPage.prototype.showMessage=function(self,msg){if(!msg)return;var msgLi='<li class="sp_message_box"><i class="fa fa-exclamation-triangle"></i> '+msg+'</li>';$(self.elem.results).empty().append(msgLi);self.calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);$(self.elem.control).hide();$(self.elem.navi).hide();};SelectPage.prototype.scrollWindow=function(self,enforce){var current_result=self.getCurrentLine(self);var target_top=(current_result&&!enforce)?current_result.offset().top:$(self.elem.container).offset().top;var target_size;self.prop.size_li=$(self.elem.results).children('li:first').outerHeight();target_size=self.prop.size_li;var client_height=$(window).height();var scroll_top=$(window).scrollTop();var scroll_bottom=scroll_top+client_height-target_size;var gap;if($(current_result).length){if(target_top<scroll_top||target_size>client_height){gap=target_top-scroll_top;}else if(target_top>scroll_bottom){gap=target_top-scroll_bottom;}else{return;}}else if(target_top<scroll_top)gap=target_top-scroll_top;window.scrollBy(0,gap);};SelectPage.prototype.setCssFocusedInput=function(self){$(self.elem.results).addClass(self.css_class.re_off);$(self.elem.combo_input).removeClass(self.css_class.input_off);};SelectPage.prototype.setCssFocusedResults=function(self){$(self.elem.results).removeClass(self.css_class.re_off);$(self.elem.combo_input).addClass(self.css_class.input_off);};SelectPage.prototype.checkValue=function(self){var now_value=$(self.elem.combo_input).val();if(now_value!=self.prop.prev_value){self.prop.prev_value=now_value;self.prop.first_show=false;if(self.option.selectOnly)self.setButtonAttrDefault();self.prop.page_suggest=1;self.prop.is_suggest=true;self.suggest(self);}};SelectPage.prototype.processKey=function(self,e){if(($.inArray(e.keyCode,[37,38,39,40,27,9])>-1&&$(self.elem.result_area).is(':visible'))||($.inArray(e.keyCode,[13,9])>-1&&self.getCurrentLine(self))){e.preventDefault();e.stopPropagation();e.cancelBubble=true;e.returnValue=false;switch(e.keyCode){case 37:if(e.shiftKey)self.firstPage(self);else self.prevPage(self);break;case 38:self.prop.key_select=true;self.prevLine(self);break;case 39:if(e.shiftKey)self.lastPage(self);else self.nextPage(self);break;case 40:if($(self.elem.results).children('li').length){self.prop.key_select=true;self.nextLine(self);}else{self.prop.is_suggest=false;self.suggest(self);}break;case 9:self.prop.key_paging=true;self.selectCurrentLine(self,true);break;case 13:self.selectCurrentLine(self,true);break;case 27:self.prop.key_paging=true;self.hideResults(self);break;}}else{if(e.keyCode!=16)self.setCssFocusedInput(self);self.inputResize(self);self.checkValue(self);}};SelectPage.prototype.abortAjax=function(self){if(self.prop.xhr){self.prop.xhr.abort();self.prop.xhr=false;}};SelectPage.prototype.suggest=function(self){var q_word;q_word=(self.prop.first_show)?'':$.trim($(self.elem.combo_input).val());q_word=q_word.split(/[\s ]+/);self.abortAjax(self);self.setLoading(self);if(self.prop.is_paging){var obj=self.getCurrentLine(self);self.prop.is_paging=(obj)?$(self.elem.results).children('li').index(obj):-1;}else if(!self.prop.is_suggest){self.prop.is_paging=0;}var which_page_num=self.prop.page_all;if(typeof self.option.data=='object')self.searchForJson(self,q_word,which_page_num);else self.searchForDb(self,q_word,which_page_num);};SelectPage.prototype.setLoading=function(self){if($(self.elem.results).html()===''){$(self.elem.container).addClass(self.css_class.container_open);}};SelectPage.prototype.searchForDb=function(self,q_word,which_page_num){if(!self.option.eAjaxSuccess&&$.isFunction(self.option.eAjaxSuccess))self.hideResults(self);var _paramsFunc=self.option.params;var _params={};var searchKey=self.option.searchField;var _orgParams={q_word:q_word,pageNumber:which_page_num,pageSize:self.option.pageSize,andOr:self.option.andOr,orderBy:self.option.orderBy,db_table:self.option.dbTable};_orgParams[searchKey]=q_word[0];console.log(q_word);if(_paramsFunc&&$.isFunction(_paramsFunc)){var result=_paramsFunc();if(result&&$.isPlainObject(result)){_params=$.extend({},_orgParams,result);}else _params=_orgParams;}else _params=_orgParams;self.prop.xhr=$.ajax({dataType:'json',url:self.option.data,type:'POST',data:_params,success:function(returnData){if(!returnData||!$.isPlainObject(returnData)){self.hideResults(self);self.ajaxErrorNotify(self,errorThrown);return;}var data;if(self.option.eAjaxSuccess&&$.isFunction(self.option.eAjaxSuccess)){data=self.option.eAjaxSuccess(returnData);}else{data=returnData;}var json={};json.originalResult=data.list;json.cnt_whole=data.totalRow;json.candidate=[];json.primaryKey=[];if(typeof json.originalResult!='object'){self.prop.xhr=null;self.notFoundSearch(self);return;}json.cnt_page=json.originalResult.length;for(var i=0;i<json.cnt_page;i++){for(var key in json.originalResult[i]){if(key==self.option.primaryKey){json.primaryKey.push(json.originalResult[i][key]);}if(key==self.option.field){json.candidate.push(json.originalResult[i][key]);}}}self.prepareResults(self,json,q_word,which_page_num);},error:function(jqXHR,textStatus,errorThrown){if(textStatus!='abort'){self.hideResults(self);self.ajaxErrorNotify(self,errorThrown);}},complete:function(){self.prop.xhr=null;}});};SelectPage.prototype.searchForJson=function(self,q_word,which_page_num){var matched=[];var esc_q=[];var sorted=[];var json={};var i=0;var arr_reg=[];do{esc_q[i]=q_word[i].replace(/\W/g,'\\$&').toString();arr_reg[i]=new RegExp(esc_q[i],'gi');i++;}while(i<q_word.length);for(i=0;i<self.option.data.length;i++){var flag=false;var row=self.option.data[i];for(var j=0;j<arr_reg.length;j++){var itemText=row[self.option.field];if(self.option.formatItem&&$.isFunction(self.option.formatItem))itemText=self.option.formatItem(row);if(itemText.match(arr_reg[j])){flag=true;if(self.option.andOr=='OR')break;}else{flag=false;if(self.option.andOr=='AND')break;}}if(flag)matched.push(row);}if(matched.length===undefined){self.notFoundSearch(self);return;}json.cnt_whole=matched.length;var reg1=new RegExp('^'+esc_q[0]+'$','gi');var reg2=new RegExp('^'+esc_q[0],'gi');var matched1=[];var matched2=[];var matched3=[];for(i=0;i<matched.length;i++){if(matched[i][self.option.orderBy[0][0]].match(reg1)){matched1.push(matched[i]);}else if(matched[i][self.option.orderBy[0][0]].match(reg2)){matched2.push(matched[i]);}else{matched3.push(matched[i]);}}if(self.option.orderBy[0][1].match(/^asc$/i)){matched1=self.sortAsc(self,matched1);matched2=self.sortAsc(self,matched2);matched3=self.sortAsc(self,matched3);}else{matched1=self.sortDesc(self,matched1);matched2=self.sortDesc(self,matched2);matched3=self.sortDesc(self,matched3);}sorted=sorted.concat(matched1).concat(matched2).concat(matched3);if(!self.prop.page_move){if(!self.option.multiple){var currentValue=$(self.elem.hidden).val();if(typeof(currentValue)!='undefined'&&$.trim(currentValue)!=''){var index=0;$.each(sorted,function(i,row){if(row[self.option.primaryKey]==currentValue){index=i+1;return false;}});which_page_num=Math.ceil(index/self.option.pageSize);if(which_page_num<1)which_page_num=1;self.prop.page_all=which_page_num;}}}else{if(sorted.length<=((which_page_num-1)*self.option.pageSize)){which_page_num=1;self.prop.page_all=1;}}var start=(which_page_num-1)*self.option.pageSize;var end=start+self.option.pageSize;json.originalResult=[];for(i=start;i<end;i++){if(sorted[i]===undefined)break;json.originalResult.push(sorted[i]);for(var key in sorted[i]){if(key==self.option.primaryKey){if(json.primaryKey===undefined)json.primaryKey=[];json.primaryKey.push(sorted[i][key]);}if(key==self.option.field){if(json.candidate===undefined)json.candidate=[];json.candidate.push(sorted[i][key]);}}}if(json.candidate===undefined)json.candidate=[];json.cnt_page=json.candidate.length;self.prepareResults(self,json,q_word,which_page_num);};SelectPage.prototype.sortAsc=function(self,arr){arr.sort(function(a,b){return a[self.option.orderBy[0][0]].localeCompare(b[self.option.orderBy[0][0]]);});return arr;};SelectPage.prototype.sortDesc=function(self,arr){arr.sort(function(a,b){return b[self.option.orderBy[0][0]].localeCompare(a[self.option.orderBy[0][0]]);});return arr;};SelectPage.prototype.notFoundSearch=function(self){$(self.elem.navi_info).text(self.message.not_found);$(self.elem.navi_p).hide();$(self.elem.results).empty();self.calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);self.setCssFocusedInput(self);};SelectPage.prototype.prepareResults=function(self,json,q_word,which_page_num){self.setNavi(self,json.cnt_whole,json.cnt_page,which_page_num);if(!json.primaryKey)json.primaryKey=false;if(self.option.selectOnly&&json.candidate.length===1&&json.candidate[0]==q_word[0]){$(self.elem.hidden).val(json.primaryKey[0]);this.setButtonAttrDefault();}var is_query=false;if(q_word&&q_word.length>0&&q_word[0])is_query=true;self.displayResults(self,json,is_query);if(self.prop.is_paging===false)self.setCssFocusedInput(self);else{if(!self.option.multiple){var liSelected=$('li.sp_selected',$(self.elem.results));if($(liSelected).size()==0){var idx=self.prop.is_paging;var limit=$(self.elem.results).children('li').length-1;if(idx>limit)idx=limit;var obj=$(self.elem.results).children('li').eq(idx);$(obj).addClass(self.css_class.select);}else $(liSelected).addClass(self.css_class.select);}self.prop.is_paging=false;self.setCssFocusedResults(self);}};SelectPage.prototype.setNavi=function(self,cnt_whole,cnt_page,page_num){var buildPageNav=function(self,pagebar,page_num,last_page){if($('li',$(pagebar)).size()==0){$(pagebar).empty();var btnclass='',isNewFontAwesome=true;$.each(document.styleSheets,function(i,n){if(n&&n.href&&n.href.indexOf('font-awesome-3.2.1')!=-1){isNewFontAwesome=false;return false;}});var iconFist='fa fa-angle-double-left',iconPrev='fa fa-angle-left',iconNext='fa fa-angle-right',iconLast='fa fa-angle-double-right';if(!isNewFontAwesome){iconFist='icon-step-backward';iconPrev='icon-backward';iconNext='icon-forward';iconLast='icon-step-forward';}if(page_num==1)btnclass=' disabled ';$(pagebar).append('<li class="csFirstPage'+btnclass+'" title="'+self.message.first_title+'" ><a href="javascript:void(0);"> <i class="'+iconFist+'"></i> </a></li>');$(pagebar).append('<li class="csPreviousPage'+btnclass+'" title="'+self.message.prev_title+'" ><a href="javascript:void(0);"><i class="'+iconPrev+'"></i></a></li>');var pageInfo=''+page_num+' 页(共'+last_page+'页)';$(pagebar).append('<li class="pageInfoBox"><a href="javascript:void(0);"> '+pageInfo+' </a></li>');if(page_num==last_page)btnclass=' disabled ';else btnclass='';$(pagebar).append('<li class="csNextPage'+btnclass+'" title="'+self.message.next_title+'" ><a href="javascript:void(0);"><i class="'+iconNext+'"></i></a></li>');$(pagebar).append('<li class="csLastPage'+btnclass+'" title="'+self.message.last_title+'" ><a href="javascript:void(0);"> <i class="'+iconLast+'"></i> </a></li>');}};var pagebar=$('ul',$(self.elem.navi));var last_page=Math.ceil(cnt_whole/self.option.pageSize);if(last_page==0)page_num=0;else{if(page_num==0)page_num=1;}buildPageNav(self,pagebar,page_num,last_page);var pageInfoBox=$('li.pageInfoBox',$(pagebar));var pageInfo=''+page_num+' 页(共'+last_page+'页)';$(pageInfoBox).html('<a href="javascript:void(0);"> '+pageInfo+' </a>');var dClass='disabled';var first=$('li.csFirstPage',$(pagebar));var previous=$('li.csPreviousPage',$(pagebar));var next=$('li.csNextPage',$(pagebar));var last=$('li.csLastPage',$(pagebar));if(page_num==1||page_num==0){if(!$(first).hasClass(dClass))$(first).addClass(dClass);if(!$(previous).hasClass(dClass))$(previous).addClass(dClass);}else{if($(first).hasClass(dClass))$(first).removeClass(dClass);if($(previous).hasClass(dClass))$(previous).removeClass(dClass);}if(page_num==last_page||last_page==0){if(!$(next).hasClass(dClass))$(next).addClass(dClass);if(!$(last).hasClass(dClass))$(last).addClass(dClass);}else{if($(next).hasClass(dClass))$(next).removeClass(dClass);if($(last).hasClass(dClass))$(last).removeClass(dClass);}if(last_page>1){if(self.prop.is_suggest)self.prop.max_suggest=last_page;else self.prop.max_all=last_page;self.ehNaviPaging();}else{}};SelectPage.prototype.displayResults=function(self,json,is_query){$(self.elem.results).empty();if(self.option.multiple&&$.type(self.option.maxSelectLimit)=='number'&&self.option.maxSelectLimit>0){var selectedSize=$('li.selected_tag',self.elem.element_box).size();if(selectedSize>0&&selectedSize>=self.option.maxSelectLimit){self.showMessage(self,'最多只能选择 '+self.option.maxSelectLimit+' 个项目');return;}}var arr_candidate=json.candidate;var arr_primary_key=json.primaryKey;var keystr=$(self.elem.hidden).val();var keyArr=keystr?keyArr=keystr.split(','):new Array();for(var i=0;i<arr_candidate.length;i++){var itemText='';if(self.option.formatItem&&$.isFunction(self.option.formatItem)){try{itemText=self.option.formatItem(json.originalResult[i]);}catch(e){console.error('formatItem内容格式化函数内容设置不正确!');itemText=arr_candidate[i];}}else itemText=arr_candidate[i];var list=$('<li>').html(itemText).attr({pkey:arr_primary_key[i],title:itemText});if($.inArray(arr_primary_key[i].toString(),keyArr)!=-1){$(list).addClass(self.css_class.selected);}$(list).data('dataObj',json.originalResult[i]);$(self.elem.results).append(list);}$(self.elem.control).show();$(self.elem.navi).show();self.calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);self.eResultList();if(is_query&&arr_candidate.length>0&&self.option.autoSelectFirst)self.nextLine(self);};SelectPage.prototype.calcWidthResults=function(self){$(self.elem.result_area).show(1,function(){if($(self.elem.container).css('position')=='static'){var offset=$(self.elem.combo_input).offset();$(self.elem.result_area).css({top:offset.top+$(self.elem.combo_input).outerHeight()+'px',left:offset.left+'px'});}else{var docWidth=$(document).width();var docHeight=$(document).height();var viewHeight=$(window).height();var offset=$(self.elem.container).offset();var screenScrollTop=$(window).scrollTop();var listWidth=$(self.elem.result_area).outerWidth();var listHeight=$(self.elem.result_area).outerHeight();var defaultLeft=self.option.multiple?-1:0;var inputHeight=$(self.elem.container).outerHeight();var left=(offset.left+listWidth)>docWidth?-(listWidth-$(self.elem.container).outerWidth()):defaultLeft;var screenTop=offset.top;var listTop=screenTop+inputHeight+listHeight;var hasOverflow=docHeight>viewHeight;var top=0;if((hasOverflow&&listTop>(viewHeight+screenScrollTop))||(!hasOverflow&&listTop>viewHeight)){top=-(listHeight+1);$(self.elem.result_area).removeClass('shadowUp shadowDown').addClass('shadowUp');}else{top=self.option.multiple?$(self.elem.container).innerHeight()+1:$(self.elem.container).outerHeight();$(self.elem.result_area).removeClass('shadowUp shadowDown').addClass('shadowDown');}$(self.elem.result_area).css({top:top+'px',left:left+'px'});}});};SelectPage.prototype.hideResults=function(self){if(self.prop.key_paging){self.scrollWindow(self,true);self.prop.key_paging=false;}self.setCssFocusedInput(self);if(self.option.autoFillResult){}$(self.elem.results).empty();$(self.elem.result_area).hide();$(self.elem.container).removeClass(self.css_class.container_open);self.abortAjax(self);self.setButtonAttrDefault();};SelectPage.prototype.firstPage=function(self){if(self.prop.page_all>1){self.prop.page_all=1;self.prop.is_paging=true;self.prop.page_move=true;self.suggest(self);}};SelectPage.prototype.prevPage=function(self){if(self.prop.page_all>1){self.prop.page_all--;self.prop.is_paging=true;self.prop.page_move=true;self.suggest(self);}};SelectPage.prototype.nextPage=function(self){if(self.prop.page_all<self.prop.max_all){self.prop.page_all++;self.prop.is_paging=true;self.prop.page_move=true;self.suggest(self);}};SelectPage.prototype.lastPage=function(self){if(self.prop.page_all<self.prop.max_all){self.prop.page_all=self.prop.max_all;self.prop.is_paging=true;self.prop.page_move=true;self.suggest(self);}};SelectPage.prototype.goPage=function(self,page){if(typeof(page)=='undefined')page=1;if(self.prop.page_all<self.prop.max_all){self.prop.page_all=page;self.prop.is_paging=true;self.prop.page_move=true;self.suggest(self);}};SelectPage.prototype.afterAction=function(self){self.inputResize(self);$(self.elem.combo_input).change();self.setCssFocusedInput(self);if(self.option.multiple){if(self.option.selectToCloseList){self.hideResults(self);$(self.elem.combo_input).blur();}else{self.suggest(self);$(self.elem.combo_input).focus();}}else{self.hideResults(self);$(self.elem.combo_input).blur();}};SelectPage.prototype.selectCurrentLine=function(self,is_enter_key){self.scrollWindow(self,true);var current=self.getCurrentLine(self);if(current){if(!self.option.multiple){$(self.elem.combo_input).val($(current).text());$(self.elem.hidden).val($(current).attr('pkey'));}else{$(self.elem.combo_input).val('');var item={text:$(current).text(),value:$(current).attr('pkey')};if(!self.isAlreadySelected(self,item)){self.addNewTag(self,item);self.tagValuesSet(self);}}if(self.option.selectOnly)self.setButtonAttrDefault();if(self.option.eSelect&&$.isFunction(self.option.eSelect))self.option.eSelect($(current).data('dataObj'));self.prop.prev_value=$(self.elem.combo_input).val();}self.afterAction(self);};SelectPage.prototype.selectAllLine=function(self){var jsonarr=new Array();$('li',self.elem.results).each(function(i,row){var item={text:$(row).text(),value:$(row).attr('pkey')};if(!self.isAlreadySelected(self,item)){self.addNewTag(self,item);self.tagValuesSet(self);}jsonarr.push($(row).data('dataObj'));});if(self.option.eSelect&&$.isFunction(self.option.eSelect))self.option.eSelect(jsonarr);self.afterAction(self);};SelectPage.prototype.unselectAllLine=function(self){var size=$('li',self.elem.results).size();$('li',self.elem.results).each(function(i,row){var key=$(row).attr('pkey');var tag=$('li.selected_tag[itemvalue="'+key+'"]',self.elem.element_box);self.removeTag(self,tag);});self.afterAction(self);if(self.option.eAjaxSuccess&&$.isFunction(self.option.eAjaxSuccess))self.option.eAjaxSuccess(size);};SelectPage.prototype.clearAll=function(self){var size=$('li.selected_tag',self.elem.element_box).size();$('li.selected_tag',self.elem.element_box).remove();$(self.elem.hidden).val('');self.afterAction(self);if(self.option.eAjaxSuccess&&$.isFunction(self.option.eAjaxSuccess))self.option.eAjaxSuccess(size);};SelectPage.prototype.clearAllSelect=function(){var self=this;if(self.option.multiple){$('li.selected_tag',self.elem.element_box).remove();$(self.elem.hidden).val('');}else{$(self.elem.combo_input).val('');$(self.elem.hidden).val('');}if($(self.elem.result_area).is(':visible'))self.hideResults(self);};SelectPage.prototype.getCurrentLine=function(self){if($(self.elem.result_area).is(':hidden'))return false;var obj=$('li.'+self.css_class.select,self.elem.results);if($(obj).size())return obj;else return false;};SelectPage.prototype.isAlreadySelected=function(self,item){var isExist=false;if(item.value){var keys=$(self.elem.hidden).val();if(keys){var karr=keys.split(',');if(karr&&karr.length>0&&$.inArray(item.value,karr)!=-1)isExist=true;}}return isExist;};SelectPage.prototype.addNewTag=function(self,item){if(!self.option.multiple||!item)return;var tmp=self.template.tag.content;tmp=tmp.replace(self.template.tag.textKey,item.text);tmp=tmp.replace(self.template.tag.valueKey,item.value);$(self.elem.combo_input).closest('li').before($(tmp));};SelectPage.prototype.removeTag=function(self,item){var key=$(item).attr('itemvalue');var keys=$(self.elem.hidden).val();if($.type(key)!='undefined'&&keys){var keyarr=keys.split(',');var index=$.inArray(key.toString(),keyarr);if(index!=-1){keyarr.splice(index,1);$(self.elem.hidden).val(keyarr.toString());}}$(item).remove();self.inputResize(self);};SelectPage.prototype.tagValuesSet=function(self){if(!self.option.multiple)return;var tags=$('li.selected_tag',$(self.elem.element_box));if(tags&&$(tags).size()>0){var result=new Array();$.each(tags,function(i,li){var v=$(li).attr('itemvalue');if($.type(v)!='undefined')result.push(v);});if(result.length>0){$(self.elem.hidden).val(result.join(','));}}};SelectPage.prototype.inputResize=function(self){if(!self.option.multiple)return;var width='';var inputLi=self.elem.combo_input.closest('li');var setDefaultSize=function(self,inputLi){inputLi.removeClass('full_width');var minimumWidth=self.elem.combo_input.val().length+1;var width=(minimumWidth*0.75)+'em';self.elem.combo_input.css('width',width);self.elem.combo_input.removeAttr('placeholder');};if($('li.selected_tag',$(self.elem.element_box)).size()==0){if(self.elem.combo_input.attr('placeholder_bak')){if(!inputLi.hasClass('full_width'))inputLi.addClass('full_width');self.elem.combo_input.attr('placeholder',self.elem.combo_input.attr('placeholder_bak'));self.elem.combo_input.removeAttr('style');}else setDefaultSize(self,inputLi);}else setDefaultSize(self,inputLi);};SelectPage.prototype.nextLine=function(self){var obj=self.getCurrentLine(self);var idx;if(!obj)idx=-1;else{idx=$(self.elem.results).children('li').index(obj);$(obj).removeClass(self.css_class.select);}idx++;if(idx<$(self.elem.results).children('li').length){var next=$(self.elem.results).children('li').eq(idx);$(next).addClass(self.css_class.select);self.setCssFocusedResults(self);}else self.setCssFocusedInput(self);self.scrollWindow(self,false);};SelectPage.prototype.prevLine=function(self){var obj=self.getCurrentLine(self);var idx;if(!obj)idx=$(self.elem.results).children('li').length;else{idx=$(self.elem.results).children('li').index(obj);$(obj).removeClass(self.css_class.select);}idx--;if(idx>-1){var prev=$(self.elem.results).children('li').eq(idx);$(prev).addClass(self.css_class.select);self.setCssFocusedResults(self);}else self.setCssFocusedInput(self);self.scrollWindow(self,false);};function Plugin(option){return this.each(function(){var $this=$(this),data=$this.data(SelectPage.dataKey),params=$.extend({},defaults,$this.data(),data&&data.option,typeof option=='object'&&option);if(!data)$this.data(SelectPage.dataKey,(data=new SelectPage(this,params)));});}function getPlugin(obj){return $(obj).siblings('input.sp_input');}function ClearSelected(){return this.each(function(){var $this=getPlugin(this),data=$this.data(SelectPage.dataKey);if(data)data.clearAllSelect();});}function SelectedRefresh(){return this.each(function(){var $this=getPlugin(this),data=$this.data(SelectPage.dataKey);if(data&&data.elem.hidden.val())data.setInitRecord(true);});}function ModifyDataSource(data){return this.each(function(){if(data&&$.isArray(data)&&data.length>0){var $this=getPlugin(this),plugin=$this.data(SelectPage.dataKey);if(plugin){plugin.clearAllSelect();plugin.option.data=data;}}});}function GetInputText(){var str='';this.each(function(){var $this=getPlugin(this),data=$this.data(SelectPage.dataKey);if(data)str+=data.elem.combo_input.val();});return str;}var old=$.fn.selectPage;$.fn.selectPage=Plugin;$.fn.selectPage.Constructor=SelectPage;$.fn.selectPageClear=ClearSelected;$.fn.selectPageRefresh=SelectedRefresh;$.fn.selectPageData=ModifyDataSource;$.fn.selectPageText=GetInputText;$.fn.selectPage.noConflict=function(){$.fn.selectPage=old;return this;};})(window.jQuery);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/sloth4413/selectpage.git
[email protected]:sloth4413/selectpage.git
sloth4413
selectpage
SelectPage
master

搜索帮助