javascript表单处理具体实现代码(表单、链接、按钮)
本文实例处理各种表单,以及链接,按钮的通用组件,教大家如何对javascript表单处理进行操作,具体内容如下
/** *GenericFormprocessingjs *@authorAnthony.chen */ /** *Pushbuttonaction[btn_action]dataintoform *Ifthereisprescript,runtheprescript */ "usestrict"; //Allajaxrequestaresynchronizedbydefault varajaxSynchronized=true; //Allajaxrequestwillbeunblockbydefault varajaxAutoUnblock=true; varajax_action_button=function(e){ varbtn=$(this); //Addprescript varpre_script; if(pre_script=btn.attr("pre_script")){ varret=eval(pre_script); if(ret==false){ returnfalse; } } varbtn_action=btn.attr('value'); if(btn_action){ $(this).closest('form').data('btn_action', {name:'btn_action',value:btn_action} ); } }; /** *UpdatetheextraformdatainFormElementwithFormelement,KeyandValue */ varajax_update_post_data=function(formEle,k,v){ varform=$(formEle); varpost_data=form.data('post_data'); if(post_data==undefined){ post_data={}; } if(v==undefined){ deletepost_data[k]; }else{ post_data[k]=v; } form.data('post_data',post_data); returntrue; }; /** *BoolCheckboxisspecialcheckboxwhichneedstokeepUNCHECKvalue *Andpostwithajaxform,theformisintheparent */ varbool_checkbox=function(){ vaript=$(this); varformEle=ipt.closest("form"); var_check=ipt.prop("checked"); if(_check){ ajax_update_post_data(formEle,ipt.attr('name')); }else{ ajax_update_post_data(formEle,ipt.attr('name'),'f'); } }; /** *Initthespinnumber */ varspin_number=function(){ varspin=$(this); varconfig={ lock:true, imageBasePath:'{webpath}/css/images/spin/', btnCss:null, txtCss:null, btnClass:'spin_btn', }; varinterval=spin.attr('interval'); if(interval){ config.interval=interval; }else{ config.interval=1; } varmin=spin.attr('min'); if(min){ config.min=min; } varmax=spin.attr('max'); if(max){ config.max=max; } spin.spin(config); returntrue; }; /** *Initthedateinput */ vardate_input=function(){ vaript=$(this); varconfig={ offset:[4,0], selectors:true, lang:'{lang}', firstDay:1, format:'yyyy-mm-dd', }; varmin=ipt.attr('min'); if(min){ config.min=min; } varmin=ipt.attr('min'); if(min){ config.min=min; } ipt.dateinput(config); returntrue; }; /** *InitthetimePicker */ vartime_picker=function(){ vaript=$(this); varconfig={}; varstep=ipt.attr("step"); if(step){ config.step=step; } ipt.timePicker(config); returntrue; }; /** *GenericAjaxFormpostfunction *Ifbtn_actionisset,thenadddataintoform *ifreturiisset,redirecttoreturi *ifreloadisset,reload *elseShowblockmessage * *theformwillbevalidated. */ varajax_form_post=function(e){ varform=$(this); varpre_script; if(pre_script=form.attr("pre_script")){ varret=eval(pre_script); if(ret==false){ returnfalse; } } varerrHint=form.find(".formError").first(); if(errHint.size()==0){ errHint=$("#pageError"); } errHint.text('').hide(); //CleanupthepageError if(!e.isDefaultPrevented()){ //Hideall.formError $.blockUI({message:"{__('L_PROCESSING')}"}); varformArray=form.serializeArray(); varbtn_action_data; varbtn_action; if(btn_action_data=form.data('btn_action')){ formArray.push(btn_action_data); form.removeData('btn_action'); btn_action=btn_action_data.value; }else{ btn_action=''; } console.log('btnaction:'+btn_action); //AddextraData varpost_data; if(post_data=form.data('post_data')){ for(varkinpost_data){ //ifpost_data[k]isarray,needmoretodo formArray.push({name:k,value:post_data[k]}); } form.removeData('post_data'); } $.post(form.attr('action'),formArray,function(json){ if($(window).data('blockUI.isBlocked')==1){ $.unblockUI(); } if(json.code===true){ varreturi=""; varretData="{__('L_PROCESSED')}!"; if(json.data){ retData=json.data; } //TODOAddsuppporttoallowsaveandstay if(btn_action=='reqonly'){ if(returi=form.attr('returi')){ $(window).data('blockUI.returi',returi); ajaxAutoUnblock=false; } $.blockUI({message:retData,css:{cursor:'pointer',padding:'4px',border:'3pxsolid#CC0000',},overlayCSS:{cursor:'pointer'}}); $(".blockUI").addClass("blockwarn"); }//ifthereisreturiset,thenreturntouri elseif(returi=form.attr('returi')){ window.location=returi; //Elseifreloadisset,thenwillbereload }elseif(form.attr('reload')!=undefined){ window.location.reload(); }else{ $.blockUI({message:retData}); $.unblockUI(); } } else{ if(typeof(json.data.errmsg)=='string'){ errHint.html(json.data).show(); //$.blockUI({message:json.data,css:{cursor:'pointer',padding:'4px',border:'3pxsolid#CC0000',},overlayCSS:{cursor:'pointer'}}); //$(".blockUI").addClass("blockwarn"); }else{ errHint.html("{Html::text(__('E_FORM'))}").show(); for(varpinjson.data){ varmsg=json.data[p]; //Processhiddenvalue,Nonehiddeninputshouldhasrefidreferedtohiddenvalue //ShowingtheServermessagetoref varele=form.find("[type=hidden][name="+p+"]"); if(ele.length){ deletejson.data.p; refid=ele.attr("id"); refname=form.find("[hidden-id="+refid+"]").attr("name"); json.data[refname]=+msg; } //Muticheckbox varele=form.find("[type=checkbox][name='"+p+"[]']"); if(ele.length){ deletejson.data.p; refname=p+'[]'; json.data[refname]=+msg; } //@END } } /* *Checkingthehiddenvalues */ form.data("validator").invalidate(json.data); }},'json'); e.preventDefault(); }else{ errHint.html("{Html::text(__('E_FORM'))}").show(); } }; /*** *Resettheinput */ varajax_post_form_hidden=function(){ varform=$(this); form.find("[hidden-id]").each(function(){ //ClearthemessageofReference varinput=$(this); varrefid=input.attr("hidden-id"); varfield=$("#"+refid+""); //SetuptheclearofErrmsg //MonitorthechangeeventonIDelement,removeerrormessage //ofRealinput field.change(function(){ //Hiddeninput varhinput=$(this); //realinput varrinput=$("[hidden-id="+hinput.attr("id")+"]").first(); form.data('validator').reset(rinput) }); }); }; varvalidate_hidden_id=function(input){ varrefid=input.attr("hidden-id"); varfield=$("#"+refid+""); varmsg=field.attr('msg'); if(!msg){ msg="{__('E_NOT_EMPTY')}"; } returnfield.val()?true:msg; }; vardata_equals_validate=function(input){ varfield; varname=input.attr("data-equals"); field=this.getInputs().filter("[name="+name+"]"); returninput.val()==field.val()?true:[name]; }; /** *Ajaxrequestthroughlink *Ifconfirmisset,confirmbeforesendrequest *Supportreturiandreload *Elseshowblockmessage */ varajax_link_req=function(){ varl=$(this); varhint=l.attr('hint'); if(hint){ varerrHint=$(l.attr('hint')); errHint.text('').hide(); } //Iftheconfirmmessageisset,thenshouldbeconfirmedfromclient if(l.attr('confirm')){ if(!confirm(l.attr('confirm'))){ returnfalse; } } $.blockUI({message:"{__('L_PROCESSING')}"}); varpre_script; if(pre_script=l.attr("pre_script")){ varret=eval(pre_script); if(ret==false){ returnfalse; } } varblock=l.attr('block'); if(block!=undefined){ ajaxAutoUnblock=false; } $.get(l.attr('href'),function(json){ if(json.code==true){ varretData="{__('L_PROCESSED')}!"; varreturi; //Ifsuccesstoexecutefuntionforeach varsuccessFunc=l.attr('success'); if(successFunc){ l.each(window[successFunc]); } if(json.data){ retData=json.data; } //IFRequirewarningbefore if(l.attr('value')=='reqonly'){ alert(retData); }elseif(returi=l.attr('returi')){ window.location=returi; } elseif(l.attr('reload')!=undefined){ window.location.reload(); } else{ $.blockUI({message:retData,css:{cursor:'pointer',padding:'4px',border:'3pxsolid#CC0000',},overlayCSS:{cursor:'pointer'}}); $(".blockUI").addClass("blockwarn"); } }else{ //$.unblockUI(); //OnlycouldsupportTexterrmsg if(hint){ errHint.text(json.data).show(); }else{ alert(json.data); } }},'json'); returnfalse; }; /** *Supportingthebuttonbasenavigation *Onlyjumptonewhref */ varbtn_nav=function(){ varinput=$(this); varhref=input.attr("href"); if(href){ window.location=href; }else{ alert("Hrefnotset"); } returnfalse; }; /** *SupportbuttonbaseAjaxgetmethodrequest *supportreturiandreload */ varbtn_req=function(){ varinput=$(this); varhref=input.attr("href"); varhint=input.attr('hint'); if(hint){ varerrHint=$(hint).first(); if(errHint.size()==0){ errHint=$("#pageError"); } errHint.text('').hide(); } varblock=input.attr('block'); if(block!=undefined){ ajaxAutoUnblock=false } $.get(href,function(json){ if(json.code==true){ varreturi; if(returi=input.attr('returi')){ window.location=returi; } elseif(input.attr("reload")!=undefined){ window.location.reload(); }else{ varretData="{__('L_PROCESSED')}!"; if(json.data){ retData=json.data; } $.blockUI({message:retData,css:{cursor:'pointer'},overlayCSS:{cursor:'pointer'}}); } }else{ if(hint){ $.unblockUI(); errHint.html(json.data.errmsg).show(); }else{ $.blockUI({message:json.data.errmsg,css:{cursor:'pointer',padding:'4px',border:'3pxsolid#CC0000',},overlayCSS:{cursor:'pointer'}}); $(".blockUI").addClass("blockwarn"); } } },'json'); returnfalse; }; /** *GenericAjaxCheckbox *ThedefaultactionispreventedandsubmitrealrequestthroughURL */ varajax_checkbox=function(){ event.preventDefault(); varaction=$(this); varurl=action.attr('url'); var_check=action.prop("checked"); console.log(_check); varop; if(_check){ op="1"; }else{ op="0"; } $.get(url+op,function(json){ if(json.code==true){ if(_check){ action.prop("checked",true); }else{ action.prop("checked",false); } returntrue; }else{ returnfalse; } },'json'); }; /** *CreteRootpicklist */ varpicklistinit=function(){ var_select=$(this); var_hidden_id=_select.attr('hidden-id'); var_un=_select.attr('un'); var_lovchildren=_select.data('lovtree').c; var_rowvalue=_select.data('rowvalue'); $("<OPTION>").append("{__('L_SELECT')}").appendTo(_select); for(var_kidin_lovchildren){ var_lov=_lovchildren[_kid]['lov']; $("<OPTION>").val(_lov.lov_id).append(_lov.v).attr('k',_lov.id).attr('is_leaf',_lov.is_leaf).appendTo(_select); } _select.change(picklistchange); //Selectthelist if(_rowvalue){ _select.find("[value="+_rowvalue[0]+"]").prop("selected",true); _select.change(); } returntrue; }; /** *Selectpicklist */ varpicklistchange=function(){ var_select=$(this); var_hidden_id=_select.attr('hidden-id'); var_un=_select.attr('un'); //Removeallthesubsequent var_lovtree=_select.data('lovtree'); var_rowvalue=_select.data('rowvalue'); _select.nextAll().remove(); //ThisisvalueofCurrentSelect var_selected=_select.find(':selected'); if(_selected.attr('is_leaf')=="{DB::T}"){ $("#"+_hidden_id).val(_select.val()); _select.after("<imgsrc='/s.gif'class='sprite_globalsuccessimg'/>"); }else{ var_val=_select.val(); var_k=_selected.attr('k'); //GettingChildrenlist if(_lovtree.c[_k].c==undefined){ returnfalse; } var_c_lovtree=_lovtree.c[_k]; var_c_select=$('<SELECT>').data('lovtree',_c_lovtree). data('rowvalue',_rowvalue). attr('hidden-id',_hidden_id).attr('un',_un). attr('name',_un+'_'+_k); $("<OPTION>").append("{__('L_SELECT')}").appendTo(_c_select); //Buildingtheoptionlist for(var_kidin_c_lovtree.c){ var_lov=_c_lovtree.c[_kid]['lov']; $("<OPTION>").val(_lov.lov_id).append(_lov.v).attr('k',_lov.id).attr('is_leaf',_lov.is_leaf).appendTo(_c_select); //Insertafter _select.after(_c_select); //Onchange } _c_select.change(picklistchange); if(_rowvalue){ _c_select.find("[value="+_rowvalue[_k]+"]").prop("selected",true); _c_select.change(); } } }; varlookup_new=function(){ varlookup=$(this); varpre_script; if(pre_script=lookup.attr("pre_script")){ varret=eval(pre_script); if(ret==false){ returnfalse; } } varurl=lookup.attr("url"); if(!url){ alert('urlnotset'); returnfalse; } varheight=lookup.attr('h'); if(!height){ height=600; } varwidth=lookup.attr('w'); if(!width){ width=800; } window.open(url,"pselect","scrollbars=yes,menubar=no,height="+height+",width="+width+",resizable=yes,toolbar=no,location=no,status=no"); returnfalse; }; /** *Lookupnewvalueforhiddenvalue */ varparent_lookup=function(){ varlookup=$(this); varpid=opener.$("#"+lookup.attr('pid')); if(!pid.length){ alert(lookup.attr('pid')+"notfound"); returnfalse; } varpname=opener.$("#"+lookup.attr('pname')); if(!pname.length){ alert(lookup.attr('pname')+"notfound"); returnfalse; } varaft_script; //Runcurrentafterscript if(aft_script=lookup.attr('aft_script')){ window.eval(aft_script); } pid.val($(this).attr("refid")); //Onlyoperationfromopenercouldtriggerchangeevent pid.change(); pname.val($(this).attr("refvalue")); pname.change(); //Parentafter_script if(aft_script=pname.attr('aft_script')){ opener.window.eval(aft_script); } if(aft_script=pid.attr('aft_script')){ opener.window.eval(aft_script); } window.close(); }; /** *Defaultuploadcomplete */ //varuploadComplete=function(event,id,fileName,responseJSON){ varuploadComplete=function(e,data){ //Tobereplacedbyjqueryuploader var_fileUpload=$(this); //console.log(_fileUpload); //console.log(data.result); if(_fileUpload.attr('reload')!=undefined){ window.location.reload(); } }; /** *Fileuploadfunction,thefollowingattributetocontrolactionofupload *'endpoint'asuploadurl *'sid'assessionid *'complete'optionaltoconfigurethecustomuploadcompletefunction */ vargenericUpload=function(dom){ varendpointurl=$(this).attr('endpoint'); varsid=$(this).attr("sid"); varcompleteFunc='uploadComplete'; //Setupcustomecompletefunction varcusComplete=$(this).attr('complete'); if(cusComplete){ completeFunc=cusComplete; } $(this).fileupload({ url:endpointurl, autoUpload:true, dataType:'json', formData:[{'sessionid':sid}], paramName:'Filedata', }).bind('fileuploaddone',window[completeFunc]); }; /** *Matchederrorswithinput *Onlymatchederrorscouldbeidentifiedhere */ varadvance_validate=function(errors,event){ varconf=this.getConf(); //looperrors $.each(errors,function(index,error){ //adderrorclassintoinputDomelement varinput=error.input; input.addClass(conf.errorClass); //gethandletotheerrorcontainer varmsg=input.data("msg.el"); //createErrordataifnotpresent,andadderrorclassforinput //"msg.el"dataislinkedtoerrormessageDomElement if(!msg){ //msg=$(conf.message).addClass(conf.messageClass).insertAfter(input); msg=$(conf.message).addClass(conf.messageClass).appendTo(input.parent()); input.data("msg.el",msg); } //clearthecontainer msg.css({visibility:'hidden'}).find("span").remove(); //populatemessages $.each(error.messages,function(i,m){ $("<span/>").html(m).appendTo(msg); }); //makesurethewidthisnotfullbodywidthsoitcanbepositionedcorrectly if(msg.outerWidth()==msg.parent().width()){ msg.add(msg.find("span")); } //insertintocorrectposition(relativetothefield) msg.css({visibility:'visible'}).fadeIn(conf.speed); msg.parent().addClass("colError"); }); }; varadvance_inputs=function(inputs){ varconf=this.getConf(); inputs.removeClass(conf.errorClass).each(function(){ varmsg=$(this).data("msg.el"); if(msg){ msg.hide(); msg.parent().removeClass("colError"); } }); if($(".colError").size()==0){ varform=$(this); varerrHint=form.find(".formError").first(); if(errHint.size()==0){ errHint=$("#pageError"); errHint.text('').hide(); } } }; /** *Whenrefnameiscontainedtobeselected */ varcheckall=function(){ varcheck=$(this); varrefname=check.attr('refname'); if(refname){ if(check.prop("checked")){ $("input[name*='"+refname+"']").prop("checked",true); }else{ $("input[name*='"+refname+"']").prop("checked",false); } } varrefclass=check.attr('refclass'); if(refclass){ if(check.prop("checked")){ $("input."+refclass).prop("checked",true); }else{ $("input."+refclass).prop("checked",false); } } }; /** *Setupreadonlycheckbox */ varreadonlyCheck=function(e){ e.preventDefault(); returnfalse; }; /** *SelectListdisable */ varreadonlySelect=function(){ $(this).prop("disabled",true); }; $(document).ready(function(){ $(document).ajaxStart(function(){ //CleanuptheAjaxrequestPageLevelError $("#pageError").text('').hide(); //CleanuptehFormError $(".formError").text('').hide(); //Blockingallajaxprocessing if(ajaxSynchronized){ $.blockUI({message:"{__('L_PROCESSING')}"}); } }); $(document).ajaxStop(function(){ if(ajaxSynchronized){ if($(window).data('blockUI.isBlocked')==1){ if(ajaxAutoUnblock){ $.unblockUI(); }else{ ajaxAutoUnblock=true; } } }else{//ChangebacktodefaultSynchronizedmodefromAsync ajaxAutoUnblock=true; ajaxSynchronized=true; } }); $(document).ajaxError(function(event,request,settings){ alert('AjaxRequestError!URL='+settings.url); if(ajaxSynchronized){ if($(window).data('blockUI.isBlocked')==1){ if(ajaxAutoUnblock){ $.unblockUI(); }else{ ajaxAutoUnblock=true; } } }else{ ajaxAutoUnblock=true; ajaxSynchronized=true; } }); //ForceunblockUI $(document).click(function(){ if($(window).data('blockUI.isBlocked')==1){ $.unblockUI(); varreturi=$(window).data('blockUI.returi'); if(returi){ window.location=returi; } }}); $.tools.validator.addEffect("advanced",advance_validate,advance_inputs); $.tools.validator.fn("[data-equals]",{"{lang}":"{__('E_NOTEQUAL')}"},data_equals_validate); $.tools.validator.fn("[hidden-id]",validate_hidden_id); $(".ajax_form_post").validator({lang:'{lang}',effect:'advanced'}).submit(ajax_form_post); $(".ajax_form_post").each(ajax_post_form_hidden); $(".spin_number").each(spin_number); $(".date_input").each(date_input); $(".time_picker").each(time_picker); $('.ajax_link_req').click(ajax_link_req); //ClientvalidationforthehiddenID $(".require_validate").validator({lang:'{lang}',effect:'advanced'}); $(".btn_nav").click(btn_nav); $(".btn_req").click(btn_req); $("button.btn_action").click(ajax_action_button); $(".lookup_new").click(lookup_new); $(".parent_lookup").click(parent_lookup); $(".ajax_checkbox").click(ajax_checkbox); $(".bool_checkbox").click(bool_checkbox); $(".checkall").click(checkall); $("img[rel]").overlay(); $("input[tip]").tooltip({position:"centerright"}); //Atlastwewilldolocalize $.tools.validator.localize("{lang}",{ '*':"{__('E_ALL')}", ':email':"{__('E_EMAIL')}", ':number':"{__('E_DECIMAL')}", ':url':"{__('E_URL')}", '[max]':"{__('E_MAX_LENGTH')}", '[min]':"{__('E_MIN_LENGTH')}", '[required]':"{__('E_NOT_EMPTY')}", }); });
以上就是本文的全部内容,希望对大家掌握javascript表单处理操作有所帮助,谢谢大家的阅读。