jquery.form.js 15 KB

1234567891011
  1. /*!
  2. * jQuery Form Plugin
  3. * version: 3.51.0-2014.06.20
  4. * Requires jQuery v1.5 or later
  5. * Copyright (c) 2014 M. Alsup
  6. * Examples and documentation at: http://malsup.com/jquery/form/
  7. * Project repository: https://github.com/malsup/form
  8. * Dual licensed under the MIT and GPL licenses.
  9. * https://github.com/malsup/form#copyright-and-license
  10. */
  11. /*global ActiveXObject */(function(b){"function"===typeof define&&define.amd?define(["jquery"],b):b("undefined"!=typeof jQuery?jQuery:window.Zepto)})(function(b){function z(a){var h=a.data;a.isDefaultPrevented()||(a.preventDefault(),b(a.target).ajaxSubmit(h))}function v(a){var h=a.target,d=b(h);if(!d.is("[type\x3dsubmit],[type\x3dimage]")){h=d.closest("[type\x3dsubmit]");if(0===h.length)return;h=h[0]}var c=this;c.clk=h;"image"==h.type&&(void 0!==a.offsetX?(c.clk_x=a.offsetX,c.clk_y=a.offsetY):"function"==typeof b.fn.offset?(d=d.offset(),c.clk_x=a.pageX-d.left,c.clk_y=a.pageY-d.top):(c.clk_x=a.pageX-h.offsetLeft,c.clk_y=a.pageY-h.offsetTop));setTimeout(function(){c.clk=c.clk_x=c.clk_y=null},100)}function r(){if(b.fn.ajaxSubmit.debug){var a="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(a):window.opera&&window.opera.postError&&window.opera.postError(a)}}var B,C;B=void 0!==b("\x3cinput type\x3d'file'/\x3e").get(0).files;C=void 0!==window.FormData;var F=!!b.fn.prop;b.fn.attr2=function(){if(!F)return this.attr.apply(this,arguments);var a=this.prop.apply(this,arguments);return a&&a.jquery||"string"===typeof a?a:this.attr.apply(this,arguments)};b.fn.ajaxSubmit=function(a){function h(c){c=b.param(c,a.traditional).split("\x26");var f=c.length,h=[],g,d;for(g=0;g<f;g++)c[g]=c[g].replace(/\+/g," "),d=c[g].split("\x3d"),h.push([decodeURIComponent(d[0]),decodeURIComponent(d[1])]);return h}function d(c){for(var f=new FormData,d=0;d<c.length;d++)f.append(c[d].name,c[d].value);if(a.extraData)for(c=h(a.extraData),d=0;d<c.length;d++)c[d]&&f.append(c[d][0],c[d][1]);a.data=null;d=b.extend(!0,{},b.ajaxSettings,a,{contentType:!1,processData:!1,cache:!1,type:g||"POST"});a.uploadProgress&&(d.xhr=function(){var c=b.ajaxSettings.xhr();c.upload&&c.upload.addEventListener("progress",function(b){var e=0,c=b.loaded||b.position,d=b.total;b.lengthComputable&&(e=Math.ceil(c/d*100));a.uploadProgress(b,c,d,e)},!1);return c});d.data=null;var l=d.beforeSend;d.beforeSend=function(b,c){c.data=a.formData?a.formData:f;l&&l.call(this,b,c)};return b.ajax(d)}function c(c){function d(a){var b=null;try{a.contentWindow&&(b=a.contentWindow.document)}catch(c){r("cannot get iframe.contentWindow document: "+c)}if(b)return b;try{b=a.contentDocument?a.contentDocument:a.document}catch(c){r("cannot get iframe.contentDocument: "+c),b=a.document}return b}function f(){function a(){try{var b=d(w).readyState;r("state \x3d "+b);b&&"uninitialized"==b.toLowerCase()&&setTimeout(a,50)}catch(c){r("Server abort: ",c," (",c.name,")"),h(2),v&&clearTimeout(v),v=void 0}}var c=n.attr2("target"),k=n.attr2("action"),m=n.attr("enctype")||n.attr("encoding")||"multipart/form-data";l.setAttribute("target",t);g&&!/post/i.test(g)||l.setAttribute("method","POST");k!=e.url&&l.setAttribute("action",e.url);e.skipEncodingOverride||g&&!/post/i.test(g)||n.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"});e.timeout&&(v=setTimeout(function(){z=!0;h(1)},e.timeout));var p=[];try{if(e.extraData)for(var q in e.extraData)e.extraData.hasOwnProperty(q)&&(b.isPlainObject(e.extraData[q])&&e.extraData[q].hasOwnProperty("name")&&e.extraData[q].hasOwnProperty("value")?p.push(b('\x3cinput type\x3d"hidden" name\x3d"'+e.extraData[q].name+'"\x3e').val(e.extraData[q].value).appendTo(l)[0]):p.push(b('\x3cinput type\x3d"hidden" name\x3d"'+q+'"\x3e').val(e.extraData[q]).appendTo(l)[0]));e.iframeTarget||x.appendTo("body");w.attachEvent?w.attachEvent("onload",h):w.addEventListener("load",h,!1);setTimeout(a,15);try{l.submit()}catch(u){document.createElement("form").submit.apply(l)}}finally{l.setAttribute("action",k),l.setAttribute("enctype",m),c?l.setAttribute("target",c):n.removeAttr("target"),b(p).remove()}}function h(a){if(!k.aborted&&!C)if(q=d(w),q||(r("cannot access response document"),a=2),1===a&&k)k.abort("timeout"),y.reject(k,"timeout");else if(2==a&&k)k.abort("server abort"),y.reject(k,"error","server abort");else if(q&&q.location.href!=e.iframeSrc||z){w.detachEvent?w.detachEvent("onload",h):w.removeEventListener("load",h,!1);a="success";var c;try{if(z)throw"timeout";var f="xml"==e.dataType||q.XMLDocument||b.isXMLDoc(q);r("isXml\x3d"+f);if(!f&&window.opera&&(null===q.body||!q.body.innerHTML)&&--B){r("requeing onLoad callback, DOM not available");setTimeout(h,250);return}var g=q.body?q.body:q.documentElement;k.responseText=g?g.innerHTML:null;k.responseXML=q.XMLDocument?q.XMLDocument:q;f&&(e.dataType="xml");k.getResponseHeader=function(a){return{"content-type":e.dataType}[a.toLowerCase()]};g&&(k.status=Number(g.getAttribute("status"))||k.status,k.statusText=g.getAttribute("statusText")||k.statusText);var l=(e.dataType||"").toLowerCase(),m=/(json|script|text)/.test(l);if(m||e.textarea){var n=q.getElementsByTagName("textarea")[0];if(n)k.responseText=n.value,k.status=Number(n.getAttribute("status"))||k.status,k.statusText=n.getAttribute("statusText")||k.statusText;else if(m){var p=q.getElementsByTagName("pre")[0],t=q.getElementsByTagName("body")[0];p?k.responseText=p.textContent?p.textContent:p.innerText:t&&(k.responseText=t.textContent?t.textContent:t.innerText)}}else"xml"==l&&!k.responseXML&&k.responseText&&(k.responseXML=E(k.responseText));try{A=G(k,l,e)}catch(D){a="parsererror",k.error=c=D||a}}catch(D){r("error caught: ",D),a="error",k.error=c=D||a}k.aborted&&(r("upload aborted"),a=null);k.status&&(a=200<=k.status&&300>k.status||304===k.status?"success":"error");"success"===a?(e.success&&e.success.call(e.context,A,"success",k),y.resolve(k.responseText,"success",k),u&&b.event.trigger("ajaxSuccess",[k,e])):a&&(void 0===c&&(c=k.statusText),e.error&&e.error.call(e.context,k,a,c),y.reject(k,"error",c),u&&b.event.trigger("ajaxError",[k,e,c]));u&&b.event.trigger("ajaxComplete",[k,e]);u&&!--b.active&&b.event.trigger("ajaxStop");e.complete&&e.complete.call(e.context,k,a);C=!0;e.timeout&&clearTimeout(v);setTimeout(function(){e.iframeTarget?x.attr("src",e.iframeSrc):x.remove();k.responseXML=null},100)}}var l=n[0],m,e,u,t,x,w,k,z,v,y=b.Deferred();y.abort=function(a){k.abort(a)};if(c)for(m=0;m<p.length;m++)c=b(p[m]),F?c.prop("disabled",!1):c.removeAttr("disabled");e=b.extend(!0,{},b.ajaxSettings,a);e.context=e.context||e;t="jqFormIO"+(new Date).getTime();e.iframeTarget?(x=b(e.iframeTarget),(m=x.attr2("name"))?t=m:x.attr2("name",t)):(x=b('\x3ciframe name\x3d"'+t+'" src\x3d"'+e.iframeSrc+'" /\x3e'),x.css({position:"absolute",top:"-1000px",left:"-1000px"}));w=x[0];k={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(a){var c="timeout"===a?"timeout":"aborted";r("aborting upload... "+c);this.aborted=1;try{w.contentWindow.document.execCommand&&w.contentWindow.document.execCommand("Stop")}catch(d){}x.attr("src",e.iframeSrc);k.error=c;e.error&&e.error.call(e.context,k,c,a);u&&b.event.trigger("ajaxError",[k,e,c]);e.complete&&e.complete.call(e.context,k,c)}};(u=e.global)&&0===b.active++&&b.event.trigger("ajaxStart");u&&b.event.trigger("ajaxSend",[k,e]);if(e.beforeSend&&!1===e.beforeSend.call(e.context,k,e))return e.global&&b.active--,y.reject(),y;if(k.aborted)return y.reject(),y;(c=l.clk)&&(m=c.name)&&!c.disabled&&(e.extraData=e.extraData||{},e.extraData[m]=c.value,"image"==c.type&&(e.extraData[m+".x"]=l.clk_x,e.extraData[m+".y"]=l.clk_y));c=b("meta[name\x3dcsrf-token]").attr("content");(m=b("meta[name\x3dcsrf-param]").attr("content"))&&c&&(e.extraData=e.extraData||{},e.extraData[m]=c);e.forceSync?f():setTimeout(f,10);var A,q,B=50,C,E=b.parseXML||function(a,b){window.ActiveXObject?(b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a)):b=(new DOMParser).parseFromString(a,"text/xml");return b&&b.documentElement&&"parsererror"!=b.documentElement.nodeName?b:null},H=b.parseJSON||function(a){return window.eval("("+a+")")},G=function(a,c,e){var d=a.getResponseHeader("content-type")||"",f="xml"===c||!c&&0<=d.indexOf("xml");a=f?a.responseXML:a.responseText;f&&"parsererror"===a.documentElement.nodeName&&b.error&&b.error("parsererror");e&&e.dataFilter&&(a=e.dataFilter(a,c));"string"===typeof a&&("json"===c||!c&&0<=d.indexOf("json")?a=H(a):("script"===c||!c&&0<=d.indexOf("javascript"))&&b.globalEval(a));return a};return y}if(!this.length)return r("ajaxSubmit: skipping submit process - no element selected"),this;var g,f,n=this;"function"==typeof a?a={success:a}:void 0===a&&(a={});g=a.type||this.attr2("method");f=a.url||this.attr2("action");(f=(f="string"===typeof f?b.trim(f):"")||window.location.href||"")&&(f=(f.match(/^([^#]+)/)||[])[1]);a=b.extend(!0,{url:f,success:b.ajaxSettings.success,type:g||b.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},a);f={};this.trigger("form-pre-serialize",[this,a,f]);if(f.veto)return r("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(a.beforeSerialize&&!1===a.beforeSerialize(this,a))return r("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var m=a.traditional;void 0===m&&(m=b.ajaxSettings.traditional);var p=[],l,u=this.formToArray(a.semantic,p);a.data&&(a.extraData=a.data,l=b.param(a.data,m));if(a.beforeSubmit&&!1===a.beforeSubmit(u,this,a))return r("ajaxSubmit: submit aborted via beforeSubmit callback"),this;this.trigger("form-submit-validate",[u,this,a,f]);if(f.veto)return r("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;f=b.param(u,m);l&&(f=f?f+"\x26"+l:l);"GET"==a.type.toUpperCase()?(a.url+=(0<=a.url.indexOf("?")?"\x26":"?")+f,a.data=null):a.data=f;var t=[];a.resetForm&&t.push(function(){n.resetForm()});a.clearForm&&t.push(function(){n.clearForm(a.includeHidden)});if(!a.dataType&&a.target){var z=a.success||function(){};t.push(function(c){var d=a.replaceTarget?"replaceWith":"html";b(a.target)[d](c).each(z,arguments)})}else a.success&&t.push(a.success);a.success=function(b,c,d){for(var f=a.context||this,g=0,h=t.length;g<h;g++)t[g].apply(f,[b,c,d||n,n])};if(a.error){var v=a.error;a.error=function(b,c,d){v.apply(a.context||this,[b,c,d,n])}}if(a.complete){var E=a.complete;a.complete=function(b,c){E.apply(a.context||this,[b,c,n])}}l=0<b("input[type\x3dfile]:enabled",this).filter(function(){return""!==b(this).val()}).length;f="multipart/form-data"==n.attr("enctype")||"multipart/form-data"==n.attr("encoding");m=B&&C;r("fileAPI :"+m);var A;!1!==a.iframe&&(a.iframe||(l||f)&&!m)?a.closeKeepAlive?b.get(a.closeKeepAlive,function(){A=c(u)}):A=c(u):A=(l||f)&&m?d(u):b.ajax(a);n.removeData("jqxhr").data("jqxhr",A);for(l=0;l<p.length;l++)p[l]=null;this.trigger("form-submit-notify",[this,a]);return this};b.fn.ajaxForm=function(a){a=a||{};a.delegation=a.delegation&&b.isFunction(b.fn.on);if(!a.delegation&&0===this.length){var h=this.selector,d=this.context;if(!b.isReady&&h)return r("DOM not ready, queuing ajaxForm"),b(function(){b(h,d).ajaxForm(a)}),this;r("terminating; zero elements found by selector"+(b.isReady?"":" (DOM not ready)"));return this}return a.delegation?(b(document).off("submit.form-plugin",this.selector,z).off("click.form-plugin",this.selector,v).on("submit.form-plugin",this.selector,a,z).on("click.form-plugin",this.selector,a,v),this):this.ajaxFormUnbind().bind("submit.form-plugin",a,z).bind("click.form-plugin",a,v)};b.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};b.fn.formToArray=function(a,h){var d=[];if(0===this.length)return d;var c=this[0],g=this.attr("id"),f=a?c.getElementsByTagName("*"):c.elements;f&&!/MSIE [678]/.test(navigator.userAgent)&&(f=b(f).get());g&&(g=b(':input[form\x3d"'+g+'"]').get(),g.length&&(f=(f||[]).concat(g)));if(!f||!f.length)return d;var n,m,p,l,r;n=0;for(r=f.length;n<r;n++)if(l=f[n],(g=l.name)&&!l.disabled)if(a&&c.clk&&"image"==l.type)c.clk==l&&(d.push({name:g,value:b(l).val(),type:l.type}),d.push({name:g+".x",value:c.clk_x},{name:g+".y",value:c.clk_y}));else if((p=b.fieldValue(l,!0))&&p.constructor==Array)for(h&&h.push(l),m=0,l=p.length;m<l;m++)d.push({name:g,value:p[m]});else if(B&&"file"==l.type)if(h&&h.push(l),p=l.files,p.length)for(m=0;m<p.length;m++)d.push({name:g,value:p[m],type:l.type});else d.push({name:g,value:"",type:l.type});else null!==p&&"undefined"!=typeof p&&(h&&h.push(l),d.push({name:g,value:p,type:l.type,required:l.required}));!a&&c.clk&&(f=b(c.clk),n=f[0],(g=n.name)&&!n.disabled&&"image"==n.type&&(d.push({name:g,value:f.val()}),d.push({name:g+".x",value:c.clk_x},{name:g+".y",value:c.clk_y})));return d};b.fn.formSerialize=function(a){return b.param(this.formToArray(a))};b.fn.fieldSerialize=function(a){var h=[];this.each(function(){var d=this.name;if(d){var c=b.fieldValue(this,a);if(c&&c.constructor==Array)for(var g=0,f=c.length;g<f;g++)h.push({name:d,value:c[g]});else null!==c&&"undefined"!=typeof c&&h.push({name:this.name,value:c})}});return b.param(h)};b.fn.fieldValue=function(a){for(var h=[],d=0,c=this.length;d<c;d++){var g=b.fieldValue(this[d],a);null===g||"undefined"==typeof g||g.constructor==Array&&!g.length||(g.constructor==Array?b.merge(h,g):h.push(g))}return h};b.fieldValue=function(a,h){var d=a.name,c=a.type,g=a.tagName.toLowerCase();void 0===h&&(h=!0);if(h&&(!d||a.disabled||"reset"==c||"button"==c||("checkbox"==c||"radio"==c)&&!a.checked||("submit"==c||"image"==c)&&a.form&&a.form.clk!=a||"select"==g&&-1==a.selectedIndex))return null;if("select"==g){var f=a.selectedIndex;if(0>f)return null;for(var d=[],g=a.options,n=(c="select-one"==c)?f+1:g.length,f=c?f:0;f<n;f++){var m=g[f];if(m.selected){var p=m.value;p||(p=m.attributes&&m.attributes.value&&!m.attributes.value.specified?m.text:m.value);if(c)return p;d.push(p)}}return d}return b(a).val()};b.fn.clearForm=function(a){return this.each(function(){b("input,select,textarea",this).clearFields(a)})};b.fn.clearFields=b.fn.clearInputs=function(a){var h=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var d=this.type,c=this.tagName.toLowerCase();h.test(d)||"textarea"==c?this.value="":"checkbox"==d||"radio"==d?this.checked=!1:"select"==c?this.selectedIndex=-1:"file"==d?/MSIE/.test(navigator.userAgent)?b(this).replaceWith(b(this).clone(!0)):b(this).val(""):a&&(!0===a&&/hidden/.test(d)||"string"==typeof a&&b(this).is(a))&&(this.value="")})};b.fn.resetForm=function(){return this.each(function(){("function"==typeof this.reset||"object"==typeof this.reset&&!this.reset.nodeType)&&this.reset()})};b.fn.enable=function(a){void 0===a&&(a=!0);return this.each(function(){this.disabled=!a})};b.fn.selected=function(a){void 0===a&&(a=!0);return this.each(function(){var h=this.type;"checkbox"==h||"radio"==h?this.checked=a:"option"==this.tagName.toLowerCase()&&(h=b(this).parent("select"),a&&h[0]&&"select-one"==h[0].type&&h.find("option").selected(!1),this.selected=a)})};b.fn.ajaxSubmit.debug=!1});