jquery.form.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. /*!
  2. * jQuery Form Plugin
  3. * version: 4.3.0
  4. * Requires jQuery v1.7.2 or later
  5. * Project repository: https://github.com/jquery-form/form
  6. * Copyright 2017 Kevin Morris
  7. * Copyright 2006 M. Alsup
  8. * Dual licensed under the LGPL-2.1+ or MIT licenses
  9. * https://github.com/jquery-form/form#license
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. */
  19. /* global ActiveXObject */
  20. /* eslint-disable */
  21. (function (factory) {
  22. if (typeof define === 'function' && define.amd) {
  23. // AMD. Register as an anonymous module.
  24. define(['jquery'], factory);
  25. } else if (typeof module === 'object' && module.exports) {
  26. // Node/CommonJS
  27. module.exports = function( root, jQuery ) {
  28. if (typeof jQuery === 'undefined') {
  29. // require('jQuery') returns a factory that requires window to build a jQuery instance, we normalize how we use modules
  30. // that require this pattern but the window provided is a noop if it's defined (how jquery works)
  31. if (typeof window !== 'undefined') {
  32. jQuery = require('jquery');
  33. }
  34. else {
  35. jQuery = require('jquery')(root);
  36. }
  37. }
  38. factory(jQuery);
  39. return jQuery;
  40. };
  41. } else {
  42. // Browser globals
  43. factory(jQuery);
  44. }
  45. }(function ($) {
  46. /* eslint-enable */
  47. 'use strict';
  48. /*
  49. Usage Note:
  50. -----------
  51. Do not use both ajaxSubmit and ajaxForm on the same form. These
  52. functions are mutually exclusive. Use ajaxSubmit if you want
  53. to bind your own submit handler to the form. For example,
  54. $(document).ready(function() {
  55. $('#myForm').on('submit', function(e) {
  56. e.preventDefault(); // <-- important
  57. $(this).ajaxSubmit({
  58. target: '#output'
  59. });
  60. });
  61. });
  62. Use ajaxForm when you want the plugin to manage all the event binding
  63. for you. For example,
  64. $(document).ready(function() {
  65. $('#myForm').ajaxForm({
  66. target: '#output'
  67. });
  68. });
  69. You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
  70. form does not have to exist when you invoke ajaxForm:
  71. $('#myForm').ajaxForm({
  72. delegation: true,
  73. target: '#output'
  74. });
  75. When using ajaxForm, the ajaxSubmit function will be invoked for you
  76. at the appropriate time.
  77. */
  78. var rCRLF = /\r?\n/g;
  79. /**
  80. * Feature detection
  81. */
  82. var feature = {};
  83. feature.fileapi = $('<input type="file">').get(0).files !== undefined;
  84. feature.formdata = (typeof window.FormData !== 'undefined');
  85. var hasProp = !!$.fn.prop;
  86. // attr2 uses prop when it can but checks the return type for
  87. // an expected string. This accounts for the case where a form
  88. // contains inputs with names like "action" or "method"; in those
  89. // cases "prop" returns the element
  90. $.fn.attr2 = function() {
  91. if (!hasProp) {
  92. return this.attr.apply(this, arguments);
  93. }
  94. var val = this.prop.apply(this, arguments);
  95. if ((val && val.jquery) || typeof val === 'string') {
  96. return val;
  97. }
  98. return this.attr.apply(this, arguments);
  99. };
  100. /**
  101. * ajaxSubmit() provides a mechanism for immediately submitting
  102. * an HTML form using AJAX.
  103. *
  104. * @param {object|string} options jquery.form.js parameters or custom url for submission
  105. * @param {object} data extraData
  106. * @param {string} dataType ajax dataType
  107. * @param {function} onSuccess ajax success callback function
  108. */
  109. $.fn.ajaxSubmit = function(options, data, dataType, onSuccess) {
  110. // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
  111. if (!this.length) {
  112. log('ajaxSubmit: skipping submit process - no element selected');
  113. return this;
  114. }
  115. /* eslint consistent-this: ["error", "$form"] */
  116. var method, action, url, isMsie, iframeSrc, $form = this;
  117. if (typeof options === 'function') {
  118. options = {success: options};
  119. } else if (typeof options === 'string' || (options === false && arguments.length > 0)) {
  120. options = {
  121. 'url' : options,
  122. 'data' : data,
  123. 'dataType' : dataType
  124. };
  125. if (typeof onSuccess === 'function') {
  126. options.success = onSuccess;
  127. }
  128. } else if (typeof options === 'undefined') {
  129. options = {};
  130. }
  131. method = options.method || options.type || this.attr2('method');
  132. action = options.url || this.attr2('action');
  133. url = (typeof action === 'string') ? $.trim(action) : '';
  134. url = url || window.location.href || '';
  135. if (url) {
  136. // clean url (don't include hash vaue)
  137. url = (url.match(/^([^#]+)/) || [])[1];
  138. }
  139. // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec.
  140. // Instead of using javascript:false always, let's only apply it for IE.
  141. isMsie = /(MSIE|Trident)/.test(navigator.userAgent || '');
  142. iframeSrc = (isMsie && /^https/i.test(window.location.href || '')) ? 'javascript:false' : 'about:blank'; // eslint-disable-line no-script-url
  143. options = $.extend(true, {
  144. url : url,
  145. success : $.ajaxSettings.success,
  146. type : method || $.ajaxSettings.type,
  147. iframeSrc : iframeSrc
  148. }, options);
  149. // hook for manipulating the form data before it is extracted;
  150. // convenient for use with rich editors like tinyMCE or FCKEditor
  151. var veto = {};
  152. this.trigger('form-pre-serialize', [this, options, veto]);
  153. if (veto.veto) {
  154. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  155. return this;
  156. }
  157. // provide opportunity to alter form data before it is serialized
  158. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  159. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  160. return this;
  161. }
  162. var traditional = options.traditional;
  163. if (typeof traditional === 'undefined') {
  164. traditional = $.ajaxSettings.traditional;
  165. }
  166. var elements = [];
  167. var qx, a = this.formToArray(options.semantic, elements, options.filtering);
  168. if (options.data) {
  169. var optionsData = $.isFunction(options.data) ? options.data(a) : options.data;
  170. options.extraData = optionsData;
  171. qx = $.param(optionsData, traditional);
  172. }
  173. // give pre-submit callback an opportunity to abort the submit
  174. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  175. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  176. return this;
  177. }
  178. // fire vetoable 'validate' event
  179. this.trigger('form-submit-validate', [a, this, options, veto]);
  180. if (veto.veto) {
  181. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  182. return this;
  183. }
  184. var q = $.param(a, traditional);
  185. if (qx) {
  186. q = (q ? (q + '&' + qx) : qx);
  187. }
  188. if (options.type.toUpperCase() === 'GET') {
  189. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  190. options.data = null; // data is null for 'get'
  191. } else {
  192. options.data = q; // data is the query string for 'post'
  193. }
  194. var callbacks = [];
  195. if (options.resetForm) {
  196. callbacks.push(function() {
  197. $form.resetForm();
  198. });
  199. }
  200. if (options.clearForm) {
  201. callbacks.push(function() {
  202. $form.clearForm(options.includeHidden);
  203. });
  204. }
  205. // perform a load on the target only if dataType is not provided
  206. if (!options.dataType && options.target) {
  207. var oldSuccess = options.success || function(){};
  208. callbacks.push(function(data, textStatus, jqXHR) {
  209. var successArguments = arguments,
  210. fn = options.replaceTarget ? 'replaceWith' : 'html';
  211. $(options.target)[fn](data).each(function(){
  212. oldSuccess.apply(this, successArguments);
  213. });
  214. });
  215. } else if (options.success) {
  216. if ($.isArray(options.success)) {
  217. $.merge(callbacks, options.success);
  218. } else {
  219. callbacks.push(options.success);
  220. }
  221. }
  222. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  223. var context = options.context || this; // jQuery 1.4+ supports scope context
  224. for (var i = 0, max = callbacks.length; i < max; i++) {
  225. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  226. }
  227. };
  228. if (options.error) {
  229. var oldError = options.error;
  230. options.error = function(xhr, status, error) {
  231. var context = options.context || this;
  232. oldError.apply(context, [xhr, status, error, $form]);
  233. };
  234. }
  235. if (options.complete) {
  236. var oldComplete = options.complete;
  237. options.complete = function(xhr, status) {
  238. var context = options.context || this;
  239. oldComplete.apply(context, [xhr, status, $form]);
  240. };
  241. }
  242. // are there files to upload?
  243. // [value] (issue #113), also see comment:
  244. // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
  245. var fileInputs = $('input[type=file]:enabled', this).filter(function() {
  246. return $(this).val() !== '';
  247. });
  248. var hasFileInputs = fileInputs.length > 0;
  249. var mp = 'multipart/form-data';
  250. var multipart = ($form.attr('enctype') === mp || $form.attr('encoding') === mp);
  251. var fileAPI = feature.fileapi && feature.formdata;
  252. log('fileAPI :' + fileAPI);
  253. var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
  254. var jqxhr;
  255. // options.iframe allows user to force iframe mode
  256. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  257. if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
  258. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  259. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  260. if (options.closeKeepAlive) {
  261. $.get(options.closeKeepAlive, function() {
  262. jqxhr = fileUploadIframe(a);
  263. });
  264. } else {
  265. jqxhr = fileUploadIframe(a);
  266. }
  267. } else if ((hasFileInputs || multipart) && fileAPI) {
  268. jqxhr = fileUploadXhr(a);
  269. } else {
  270. jqxhr = $.ajax(options);
  271. }
  272. $form.removeData('jqxhr').data('jqxhr', jqxhr);
  273. // clear element array
  274. for (var k = 0; k < elements.length; k++) {
  275. elements[k] = null;
  276. }
  277. // fire 'notify' event
  278. this.trigger('form-submit-notify', [this, options]);
  279. return this;
  280. // utility fn for deep serialization
  281. function deepSerialize(extraData) {
  282. var serialized = $.param(extraData, options.traditional).split('&');
  283. var len = serialized.length;
  284. var result = [];
  285. var i, part;
  286. for (i = 0; i < len; i++) {
  287. // #252; undo param space replacement
  288. serialized[i] = serialized[i].replace(/\+/g, ' ');
  289. part = serialized[i].split('=');
  290. // #278; use array instead of object storage, favoring array serializations
  291. result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
  292. }
  293. return result;
  294. }
  295. // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
  296. function fileUploadXhr(a) {
  297. var formdata = new FormData();
  298. for (var i = 0; i < a.length; i++) {
  299. formdata.append(a[i].name, a[i].value);
  300. }
  301. if (options.extraData) {
  302. var serializedData = deepSerialize(options.extraData);
  303. for (i = 0; i < serializedData.length; i++) {
  304. if (serializedData[i]) {
  305. formdata.append(serializedData[i][0], serializedData[i][1]);
  306. }
  307. }
  308. }
  309. options.data = null;
  310. var s = $.extend(true, {}, $.ajaxSettings, options, {
  311. contentType : false,
  312. processData : false,
  313. cache : false,
  314. type : method || 'POST'
  315. });
  316. if (options.uploadProgress) {
  317. // workaround because jqXHR does not expose upload property
  318. s.xhr = function() {
  319. var xhr = $.ajaxSettings.xhr();
  320. if (xhr.upload) {
  321. xhr.upload.addEventListener('progress', function(event) {
  322. var percent = 0;
  323. var position = event.loaded || event.position; /* event.position is deprecated */
  324. var total = event.total;
  325. if (event.lengthComputable) {
  326. percent = Math.ceil(position / total * 100);
  327. }
  328. options.uploadProgress(event, position, total, percent);
  329. }, false);
  330. }
  331. return xhr;
  332. };
  333. }
  334. s.data = null;
  335. var beforeSend = s.beforeSend;
  336. s.beforeSend = function(xhr, o) {
  337. // Send FormData() provided by user
  338. if (options.formData) {
  339. o.data = options.formData;
  340. } else {
  341. o.data = formdata;
  342. }
  343. if (beforeSend) {
  344. beforeSend.call(this, xhr, o);
  345. }
  346. };
  347. return $.ajax(s);
  348. }
  349. // private function for handling file uploads (hat tip to YAHOO!)
  350. function fileUploadIframe(a) {
  351. var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
  352. var deferred = $.Deferred();
  353. // #341
  354. deferred.abort = function(status) {
  355. xhr.abort(status);
  356. };
  357. if (a) {
  358. // ensure that every serialized input is still enabled
  359. for (i = 0; i < elements.length; i++) {
  360. el = $(elements[i]);
  361. if (hasProp) {
  362. el.prop('disabled', false);
  363. } else {
  364. el.removeAttr('disabled');
  365. }
  366. }
  367. }
  368. s = $.extend(true, {}, $.ajaxSettings, options);
  369. s.context = s.context || s;
  370. id = 'jqFormIO' + new Date().getTime();
  371. var ownerDocument = form.ownerDocument;
  372. var $body = $form.closest('body');
  373. if (s.iframeTarget) {
  374. $io = $(s.iframeTarget, ownerDocument);
  375. n = $io.attr2('name');
  376. if (!n) {
  377. $io.attr2('name', id);
  378. } else {
  379. id = n;
  380. }
  381. } else {
  382. $io = $('<iframe name="' + id + '" src="' + s.iframeSrc + '" />', ownerDocument);
  383. $io.css({position: 'absolute', top: '-1000px', left: '-1000px'});
  384. }
  385. io = $io[0];
  386. xhr = { // mock object
  387. aborted : 0,
  388. responseText : null,
  389. responseXML : null,
  390. status : 0,
  391. statusText : 'n/a',
  392. getAllResponseHeaders : function() {},
  393. getResponseHeader : function() {},
  394. setRequestHeader : function() {},
  395. abort : function(status) {
  396. var e = (status === 'timeout' ? 'timeout' : 'aborted');
  397. log('aborting upload... ' + e);
  398. this.aborted = 1;
  399. try { // #214, #257
  400. if (io.contentWindow.document.execCommand) {
  401. io.contentWindow.document.execCommand('Stop');
  402. }
  403. } catch (ignore) {}
  404. $io.attr('src', s.iframeSrc); // abort op in progress
  405. xhr.error = e;
  406. if (s.error) {
  407. s.error.call(s.context, xhr, e, status);
  408. }
  409. if (g) {
  410. $.event.trigger('ajaxError', [xhr, s, e]);
  411. }
  412. if (s.complete) {
  413. s.complete.call(s.context, xhr, e);
  414. }
  415. }
  416. };
  417. g = s.global;
  418. // trigger ajax global events so that activity/block indicators work like normal
  419. if (g && $.active++ === 0) {
  420. $.event.trigger('ajaxStart');
  421. }
  422. if (g) {
  423. $.event.trigger('ajaxSend', [xhr, s]);
  424. }
  425. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  426. if (s.global) {
  427. $.active--;
  428. }
  429. deferred.reject();
  430. return deferred;
  431. }
  432. if (xhr.aborted) {
  433. deferred.reject();
  434. return deferred;
  435. }
  436. // add submitting element to data if we know it
  437. sub = form.clk;
  438. if (sub) {
  439. n = sub.name;
  440. if (n && !sub.disabled) {
  441. s.extraData = s.extraData || {};
  442. s.extraData[n] = sub.value;
  443. if (sub.type === 'image') {
  444. s.extraData[n + '.x'] = form.clk_x;
  445. s.extraData[n + '.y'] = form.clk_y;
  446. }
  447. }
  448. }
  449. var CLIENT_TIMEOUT_ABORT = 1;
  450. var SERVER_ABORT = 2;
  451. function getDoc(frame) {
  452. /* it looks like contentWindow or contentDocument do not
  453. * carry the protocol property in ie8, when running under ssl
  454. * frame.document is the only valid response document, since
  455. * the protocol is know but not on the other two objects. strange?
  456. * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
  457. */
  458. var doc = null;
  459. // IE8 cascading access check
  460. try {
  461. if (frame.contentWindow) {
  462. doc = frame.contentWindow.document;
  463. }
  464. } catch (err) {
  465. // IE8 access denied under ssl & missing protocol
  466. log('cannot get iframe.contentWindow document: ' + err);
  467. }
  468. if (doc) { // successful getting content
  469. return doc;
  470. }
  471. try { // simply checking may throw in ie8 under ssl or mismatched protocol
  472. doc = frame.contentDocument ? frame.contentDocument : frame.document;
  473. } catch (err) {
  474. // last attempt
  475. log('cannot get iframe.contentDocument: ' + err);
  476. doc = frame.document;
  477. }
  478. return doc;
  479. }
  480. // Rails CSRF hack (thanks to Yvan Barthelemy)
  481. var csrf_token = $('meta[name=csrf-token]').attr('content');
  482. var csrf_param = $('meta[name=csrf-param]').attr('content');
  483. if (csrf_param && csrf_token) {
  484. s.extraData = s.extraData || {};
  485. s.extraData[csrf_param] = csrf_token;
  486. }
  487. // take a breath so that pending repaints get some cpu time before the upload starts
  488. function doSubmit() {
  489. // make sure form attrs are set
  490. var t = $form.attr2('target'),
  491. a = $form.attr2('action'),
  492. mp = 'multipart/form-data',
  493. et = $form.attr('enctype') || $form.attr('encoding') || mp;
  494. // update form attrs in IE friendly way
  495. form.setAttribute('target', id);
  496. if (!method || /post/i.test(method)) {
  497. form.setAttribute('method', 'POST');
  498. }
  499. if (a !== s.url) {
  500. form.setAttribute('action', s.url);
  501. }
  502. // ie borks in some cases when setting encoding
  503. if (!s.skipEncodingOverride && (!method || /post/i.test(method))) {
  504. $form.attr({
  505. encoding : 'multipart/form-data',
  506. enctype : 'multipart/form-data'
  507. });
  508. }
  509. // support timout
  510. if (s.timeout) {
  511. timeoutHandle = setTimeout(function() {
  512. timedOut = true; cb(CLIENT_TIMEOUT_ABORT);
  513. }, s.timeout);
  514. }
  515. // look for server aborts
  516. function checkState() {
  517. try {
  518. var state = getDoc(io).readyState;
  519. log('state = ' + state);
  520. if (state && state.toLowerCase() === 'uninitialized') {
  521. setTimeout(checkState, 50);
  522. }
  523. } catch (e) {
  524. log('Server abort: ', e, ' (', e.name, ')');
  525. cb(SERVER_ABORT); // eslint-disable-line callback-return
  526. if (timeoutHandle) {
  527. clearTimeout(timeoutHandle);
  528. }
  529. timeoutHandle = undefined;
  530. }
  531. }
  532. // add "extra" data to form if provided in options
  533. var extraInputs = [];
  534. try {
  535. if (s.extraData) {
  536. for (var n in s.extraData) {
  537. if (s.extraData.hasOwnProperty(n)) {
  538. // if using the $.param format that allows for multiple values with the same name
  539. if ($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
  540. extraInputs.push(
  541. $('<input type="hidden" name="' + s.extraData[n].name + '">', ownerDocument).val(s.extraData[n].value)
  542. .appendTo(form)[0]);
  543. } else {
  544. extraInputs.push(
  545. $('<input type="hidden" name="' + n + '">', ownerDocument).val(s.extraData[n])
  546. .appendTo(form)[0]);
  547. }
  548. }
  549. }
  550. }
  551. if (!s.iframeTarget) {
  552. // add iframe to doc and submit the form
  553. $io.appendTo($body);
  554. }
  555. if (io.attachEvent) {
  556. io.attachEvent('onload', cb);
  557. } else {
  558. io.addEventListener('load', cb, false);
  559. }
  560. setTimeout(checkState, 15);
  561. try {
  562. form.submit();
  563. } catch (err) {
  564. // just in case form has element with name/id of 'submit'
  565. var submitFn = document.createElement('form').submit;
  566. submitFn.apply(form);
  567. }
  568. } finally {
  569. // reset attrs and remove "extra" input elements
  570. form.setAttribute('action', a);
  571. form.setAttribute('enctype', et); // #380
  572. if (t) {
  573. form.setAttribute('target', t);
  574. } else {
  575. $form.removeAttr('target');
  576. }
  577. $(extraInputs).remove();
  578. }
  579. }
  580. if (s.forceSync) {
  581. doSubmit();
  582. } else {
  583. setTimeout(doSubmit, 10); // this lets dom updates render
  584. }
  585. var data, doc, domCheckCount = 50, callbackProcessed;
  586. function cb(e) {
  587. if (xhr.aborted || callbackProcessed) {
  588. return;
  589. }
  590. doc = getDoc(io);
  591. if (!doc) {
  592. log('cannot access response document');
  593. e = SERVER_ABORT;
  594. }
  595. if (e === CLIENT_TIMEOUT_ABORT && xhr) {
  596. xhr.abort('timeout');
  597. deferred.reject(xhr, 'timeout');
  598. return;
  599. }
  600. if (e === SERVER_ABORT && xhr) {
  601. xhr.abort('server abort');
  602. deferred.reject(xhr, 'error', 'server abort');
  603. return;
  604. }
  605. if (!doc || doc.location.href === s.iframeSrc) {
  606. // response not received yet
  607. if (!timedOut) {
  608. return;
  609. }
  610. }
  611. if (io.detachEvent) {
  612. io.detachEvent('onload', cb);
  613. } else {
  614. io.removeEventListener('load', cb, false);
  615. }
  616. var status = 'success', errMsg;
  617. try {
  618. if (timedOut) {
  619. throw 'timeout';
  620. }
  621. var isXml = s.dataType === 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  622. log('isXml=' + isXml);
  623. if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
  624. if (--domCheckCount) {
  625. // in some browsers (Opera) the iframe DOM is not always traversable when
  626. // the onload callback fires, so we loop a bit to accommodate
  627. log('requeing onLoad callback, DOM not available');
  628. setTimeout(cb, 250);
  629. return;
  630. }
  631. // let this fall through because server response could be an empty document
  632. // log('Could not access iframe DOM after mutiple tries.');
  633. // throw 'DOMException: not available';
  634. }
  635. // log('response detected');
  636. var docRoot = doc.body ? doc.body : doc.documentElement;
  637. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  638. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  639. if (isXml) {
  640. s.dataType = 'xml';
  641. }
  642. xhr.getResponseHeader = function(header){
  643. var headers = {'content-type': s.dataType};
  644. return headers[header.toLowerCase()];
  645. };
  646. // support for XHR 'status' & 'statusText' emulation :
  647. if (docRoot) {
  648. xhr.status = Number(docRoot.getAttribute('status')) || xhr.status;
  649. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  650. }
  651. var dt = (s.dataType || '').toLowerCase();
  652. var scr = /(json|script|text)/.test(dt);
  653. if (scr || s.textarea) {
  654. // see if user embedded response in textarea
  655. var ta = doc.getElementsByTagName('textarea')[0];
  656. if (ta) {
  657. xhr.responseText = ta.value;
  658. // support for XHR 'status' & 'statusText' emulation :
  659. xhr.status = Number(ta.getAttribute('status')) || xhr.status;
  660. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  661. } else if (scr) {
  662. // account for browsers injecting pre around json response
  663. var pre = doc.getElementsByTagName('pre')[0];
  664. var b = doc.getElementsByTagName('body')[0];
  665. if (pre) {
  666. xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
  667. } else if (b) {
  668. xhr.responseText = b.textContent ? b.textContent : b.innerText;
  669. }
  670. }
  671. } else if (dt === 'xml' && !xhr.responseXML && xhr.responseText) {
  672. xhr.responseXML = toXml(xhr.responseText); // eslint-disable-line no-use-before-define
  673. }
  674. try {
  675. data = httpData(xhr, dt, s); // eslint-disable-line no-use-before-define
  676. } catch (err) {
  677. status = 'parsererror';
  678. xhr.error = errMsg = (err || status);
  679. }
  680. } catch (err) {
  681. log('error caught: ', err);
  682. status = 'error';
  683. xhr.error = errMsg = (err || status);
  684. }
  685. if (xhr.aborted) {
  686. log('upload aborted');
  687. status = null;
  688. }
  689. if (xhr.status) { // we've set xhr.status
  690. status = ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) ? 'success' : 'error';
  691. }
  692. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  693. if (status === 'success') {
  694. if (s.success) {
  695. s.success.call(s.context, data, 'success', xhr);
  696. }
  697. deferred.resolve(xhr.responseText, 'success', xhr);
  698. if (g) {
  699. $.event.trigger('ajaxSuccess', [xhr, s]);
  700. }
  701. } else if (status) {
  702. if (typeof errMsg === 'undefined') {
  703. errMsg = xhr.statusText;
  704. }
  705. if (s.error) {
  706. s.error.call(s.context, xhr, status, errMsg);
  707. }
  708. deferred.reject(xhr, 'error', errMsg);
  709. if (g) {
  710. $.event.trigger('ajaxError', [xhr, s, errMsg]);
  711. }
  712. }
  713. if (g) {
  714. $.event.trigger('ajaxComplete', [xhr, s]);
  715. }
  716. if (g && !--$.active) {
  717. $.event.trigger('ajaxStop');
  718. }
  719. if (s.complete) {
  720. s.complete.call(s.context, xhr, status);
  721. }
  722. callbackProcessed = true;
  723. if (s.timeout) {
  724. clearTimeout(timeoutHandle);
  725. }
  726. // clean up
  727. setTimeout(function() {
  728. if (!s.iframeTarget) {
  729. $io.remove();
  730. } else { // adding else to clean up existing iframe response.
  731. $io.attr('src', s.iframeSrc);
  732. }
  733. xhr.responseXML = null;
  734. }, 100);
  735. }
  736. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  737. if (window.ActiveXObject) {
  738. doc = new ActiveXObject('Microsoft.XMLDOM');
  739. doc.async = 'false';
  740. doc.loadXML(s);
  741. } else {
  742. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  743. }
  744. return (doc && doc.documentElement && doc.documentElement.nodeName !== 'parsererror') ? doc : null;
  745. };
  746. var parseJSON = $.parseJSON || function(s) {
  747. /* jslint evil:true */
  748. return window['eval']('(' + s + ')'); // eslint-disable-line dot-notation
  749. };
  750. var httpData = function(xhr, type, s) { // mostly lifted from jq1.4.4
  751. var ct = xhr.getResponseHeader('content-type') || '',
  752. xml = ((type === 'xml' || !type) && ct.indexOf('xml') >= 0),
  753. data = xml ? xhr.responseXML : xhr.responseText;
  754. if (xml && data.documentElement.nodeName === 'parsererror') {
  755. if ($.error) {
  756. $.error('parsererror');
  757. }
  758. }
  759. if (s && s.dataFilter) {
  760. data = s.dataFilter(data, type);
  761. }
  762. if (typeof data === 'string') {
  763. if ((type === 'json' || !type) && ct.indexOf('json') >= 0) {
  764. data = parseJSON(data);
  765. } else if ((type === 'script' || !type) && ct.indexOf('javascript') >= 0) {
  766. $.globalEval(data);
  767. }
  768. }
  769. return data;
  770. };
  771. return deferred;
  772. }
  773. };
  774. /**
  775. * ajaxForm() provides a mechanism for fully automating form submission.
  776. *
  777. * The advantages of using this method instead of ajaxSubmit() are:
  778. *
  779. * 1: This method will include coordinates for <input type="image"> elements (if the element
  780. * is used to submit the form).
  781. * 2. This method will include the submit element's name/value data (for the element that was
  782. * used to submit the form).
  783. * 3. This method binds the submit() method to the form for you.
  784. *
  785. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  786. * passes the options argument along after properly binding events for submit elements and
  787. * the form itself.
  788. */
  789. $.fn.ajaxForm = function(options, data, dataType, onSuccess) {
  790. if (typeof options === 'string' || (options === false && arguments.length > 0)) {
  791. options = {
  792. 'url' : options,
  793. 'data' : data,
  794. 'dataType' : dataType
  795. };
  796. if (typeof onSuccess === 'function') {
  797. options.success = onSuccess;
  798. }
  799. }
  800. options = options || {};
  801. options.delegation = options.delegation && $.isFunction($.fn.on);
  802. // in jQuery 1.3+ we can fix mistakes with the ready state
  803. if (!options.delegation && this.length === 0) {
  804. var o = {s: this.selector, c: this.context};
  805. if (!$.isReady && o.s) {
  806. log('DOM not ready, queuing ajaxForm');
  807. $(function() {
  808. $(o.s, o.c).ajaxForm(options);
  809. });
  810. return this;
  811. }
  812. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  813. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  814. return this;
  815. }
  816. if (options.delegation) {
  817. $(document)
  818. .off('submit.form-plugin', this.selector, doAjaxSubmit)
  819. .off('click.form-plugin', this.selector, captureSubmittingElement)
  820. .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
  821. .on('click.form-plugin', this.selector, options, captureSubmittingElement);
  822. return this;
  823. }
  824. if (options.beforeFormUnbind) {
  825. options.beforeFormUnbind(this, options);
  826. }
  827. return this.ajaxFormUnbind()
  828. .on('submit.form-plugin', options, doAjaxSubmit)
  829. .on('click.form-plugin', options, captureSubmittingElement);
  830. };
  831. // private event handlers
  832. function doAjaxSubmit(e) {
  833. /* jshint validthis:true */
  834. var options = e.data;
  835. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  836. e.preventDefault();
  837. $(e.target).closest('form').ajaxSubmit(options); // #365
  838. }
  839. }
  840. function captureSubmittingElement(e) {
  841. /* jshint validthis:true */
  842. var target = e.target;
  843. var $el = $(target);
  844. if (!$el.is('[type=submit],[type=image]')) {
  845. // is this a child element of the submit el? (ex: a span within a button)
  846. var t = $el.closest('[type=submit]');
  847. if (t.length === 0) {
  848. return;
  849. }
  850. target = t[0];
  851. }
  852. var form = target.form;
  853. form.clk = target;
  854. if (target.type === 'image') {
  855. if (typeof e.offsetX !== 'undefined') {
  856. form.clk_x = e.offsetX;
  857. form.clk_y = e.offsetY;
  858. } else if (typeof $.fn.offset === 'function') {
  859. var offset = $el.offset();
  860. form.clk_x = e.pageX - offset.left;
  861. form.clk_y = e.pageY - offset.top;
  862. } else {
  863. form.clk_x = e.pageX - target.offsetLeft;
  864. form.clk_y = e.pageY - target.offsetTop;
  865. }
  866. }
  867. // clear form vars
  868. setTimeout(function() {
  869. form.clk = form.clk_x = form.clk_y = null;
  870. }, 100);
  871. }
  872. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  873. $.fn.ajaxFormUnbind = function() {
  874. return this.off('submit.form-plugin click.form-plugin');
  875. };
  876. /**
  877. * formToArray() gathers form element data into an array of objects that can
  878. * be passed to any of the following ajax functions: $.get, $.post, or load.
  879. * Each object in the array has both a 'name' and 'value' property. An example of
  880. * an array for a simple login form might be:
  881. *
  882. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  883. *
  884. * It is this array that is passed to pre-submit callback functions provided to the
  885. * ajaxSubmit() and ajaxForm() methods.
  886. */
  887. $.fn.formToArray = function(semantic, elements, filtering) {
  888. var a = [];
  889. if (this.length === 0) {
  890. return a;
  891. }
  892. var form = this[0];
  893. var formId = this.attr('id');
  894. var els = (semantic || typeof form.elements === 'undefined') ? form.getElementsByTagName('*') : form.elements;
  895. var els2;
  896. if (els) {
  897. els = $.makeArray(els); // convert to standard array
  898. }
  899. // #386; account for inputs outside the form which use the 'form' attribute
  900. // FinesseRus: in non-IE browsers outside fields are already included in form.elements.
  901. if (formId && (semantic || /(Edge|Trident)\//.test(navigator.userAgent))) {
  902. els2 = $(':input[form="' + formId + '"]').get(); // hat tip @thet
  903. if (els2.length) {
  904. els = (els || []).concat(els2);
  905. }
  906. }
  907. if (!els || !els.length) {
  908. return a;
  909. }
  910. if ($.isFunction(filtering)) {
  911. els = $.map(els, filtering);
  912. }
  913. var i, j, n, v, el, max, jmax;
  914. for (i = 0, max = els.length; i < max; i++) {
  915. el = els[i];
  916. n = el.name;
  917. if (!n || el.disabled) {
  918. continue;
  919. }
  920. if (semantic && form.clk && el.type === 'image') {
  921. // handle image inputs on the fly when semantic == true
  922. if (form.clk === el) {
  923. a.push({name: n, value: $(el).val(), type: el.type});
  924. a.push({name: n + '.x', value: form.clk_x}, {name: n + '.y', value: form.clk_y});
  925. }
  926. continue;
  927. }
  928. v = $.fieldValue(el, true);
  929. if (v && v.constructor === Array) {
  930. if (elements) {
  931. elements.push(el);
  932. }
  933. for (j = 0, jmax = v.length; j < jmax; j++) {
  934. a.push({name: n, value: v[j]});
  935. }
  936. } else if (feature.fileapi && el.type === 'file') {
  937. if (elements) {
  938. elements.push(el);
  939. }
  940. var files = el.files;
  941. if (files.length) {
  942. for (j = 0; j < files.length; j++) {
  943. a.push({name: n, value: files[j], type: el.type});
  944. }
  945. } else {
  946. // #180
  947. a.push({name: n, value: '', type: el.type});
  948. }
  949. } else if (v !== null && typeof v !== 'undefined') {
  950. if (elements) {
  951. elements.push(el);
  952. }
  953. a.push({name: n, value: v, type: el.type, required: el.required});
  954. }
  955. }
  956. if (!semantic && form.clk) {
  957. // input type=='image' are not found in elements array! handle it here
  958. var $input = $(form.clk), input = $input[0];
  959. n = input.name;
  960. if (n && !input.disabled && input.type === 'image') {
  961. a.push({name: n, value: $input.val()});
  962. a.push({name: n + '.x', value: form.clk_x}, {name: n + '.y', value: form.clk_y});
  963. }
  964. }
  965. return a;
  966. };
  967. /**
  968. * Serializes form data into a 'submittable' string. This method will return a string
  969. * in the format: name1=value1&amp;name2=value2
  970. */
  971. $.fn.formSerialize = function(semantic) {
  972. // hand off to jQuery.param for proper encoding
  973. return $.param(this.formToArray(semantic));
  974. };
  975. /**
  976. * Serializes all field elements in the jQuery object into a query string.
  977. * This method will return a string in the format: name1=value1&amp;name2=value2
  978. */
  979. $.fn.fieldSerialize = function(successful) {
  980. var a = [];
  981. this.each(function() {
  982. var n = this.name;
  983. if (!n) {
  984. return;
  985. }
  986. var v = $.fieldValue(this, successful);
  987. if (v && v.constructor === Array) {
  988. for (var i = 0, max = v.length; i < max; i++) {
  989. a.push({name: n, value: v[i]});
  990. }
  991. } else if (v !== null && typeof v !== 'undefined') {
  992. a.push({name: this.name, value: v});
  993. }
  994. });
  995. // hand off to jQuery.param for proper encoding
  996. return $.param(a);
  997. };
  998. /**
  999. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  1000. *
  1001. * <form><fieldset>
  1002. * <input name="A" type="text">
  1003. * <input name="A" type="text">
  1004. * <input name="B" type="checkbox" value="B1">
  1005. * <input name="B" type="checkbox" value="B2">
  1006. * <input name="C" type="radio" value="C1">
  1007. * <input name="C" type="radio" value="C2">
  1008. * </fieldset></form>
  1009. *
  1010. * var v = $('input[type=text]').fieldValue();
  1011. * // if no values are entered into the text inputs
  1012. * v === ['','']
  1013. * // if values entered into the text inputs are 'foo' and 'bar'
  1014. * v === ['foo','bar']
  1015. *
  1016. * var v = $('input[type=checkbox]').fieldValue();
  1017. * // if neither checkbox is checked
  1018. * v === undefined
  1019. * // if both checkboxes are checked
  1020. * v === ['B1', 'B2']
  1021. *
  1022. * var v = $('input[type=radio]').fieldValue();
  1023. * // if neither radio is checked
  1024. * v === undefined
  1025. * // if first radio is checked
  1026. * v === ['C1']
  1027. *
  1028. * The successful argument controls whether or not the field element must be 'successful'
  1029. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  1030. * The default value of the successful argument is true. If this value is false the value(s)
  1031. * for each element is returned.
  1032. *
  1033. * Note: This method *always* returns an array. If no valid value can be determined the
  1034. * array will be empty, otherwise it will contain one or more values.
  1035. */
  1036. $.fn.fieldValue = function(successful) {
  1037. for (var val = [], i = 0, max = this.length; i < max; i++) {
  1038. var el = this[i];
  1039. var v = $.fieldValue(el, successful);
  1040. if (v === null || typeof v === 'undefined' || (v.constructor === Array && !v.length)) {
  1041. continue;
  1042. }
  1043. if (v.constructor === Array) {
  1044. $.merge(val, v);
  1045. } else {
  1046. val.push(v);
  1047. }
  1048. }
  1049. return val;
  1050. };
  1051. /**
  1052. * Returns the value of the field element.
  1053. */
  1054. $.fieldValue = function(el, successful) {
  1055. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  1056. if (typeof successful === 'undefined') {
  1057. successful = true;
  1058. }
  1059. /* eslint-disable no-mixed-operators */
  1060. if (successful && (!n || el.disabled || t === 'reset' || t === 'button' ||
  1061. (t === 'checkbox' || t === 'radio') && !el.checked ||
  1062. (t === 'submit' || t === 'image') && el.form && el.form.clk !== el ||
  1063. tag === 'select' && el.selectedIndex === -1)) {
  1064. /* eslint-enable no-mixed-operators */
  1065. return null;
  1066. }
  1067. if (tag === 'select') {
  1068. var index = el.selectedIndex;
  1069. if (index < 0) {
  1070. return null;
  1071. }
  1072. var a = [], ops = el.options;
  1073. var one = (t === 'select-one');
  1074. var max = (one ? index + 1 : ops.length);
  1075. for (var i = (one ? index : 0); i < max; i++) {
  1076. var op = ops[i];
  1077. if (op.selected && !op.disabled) {
  1078. var v = op.value;
  1079. if (!v) { // extra pain for IE...
  1080. v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
  1081. }
  1082. if (one) {
  1083. return v;
  1084. }
  1085. a.push(v);
  1086. }
  1087. }
  1088. return a;
  1089. }
  1090. return $(el).val().replace(rCRLF, '\r\n');
  1091. };
  1092. /**
  1093. * Clears the form data. Takes the following actions on the form's input fields:
  1094. * - input text fields will have their 'value' property set to the empty string
  1095. * - select elements will have their 'selectedIndex' property set to -1
  1096. * - checkbox and radio inputs will have their 'checked' property set to false
  1097. * - inputs of type submit, button, reset, and hidden will *not* be effected
  1098. * - button elements will *not* be effected
  1099. */
  1100. $.fn.clearForm = function(includeHidden) {
  1101. return this.each(function() {
  1102. $('input,select,textarea', this).clearFields(includeHidden);
  1103. });
  1104. };
  1105. /**
  1106. * Clears the selected form elements.
  1107. */
  1108. $.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
  1109. var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
  1110. return this.each(function() {
  1111. var t = this.type, tag = this.tagName.toLowerCase();
  1112. if (re.test(t) || tag === 'textarea') {
  1113. this.value = '';
  1114. } else if (t === 'checkbox' || t === 'radio') {
  1115. this.checked = false;
  1116. } else if (tag === 'select') {
  1117. this.selectedIndex = -1;
  1118. } else if (t === 'file') {
  1119. if (/MSIE/.test(navigator.userAgent)) {
  1120. $(this).replaceWith($(this).clone(true));
  1121. } else {
  1122. $(this).val('');
  1123. }
  1124. } else if (includeHidden) {
  1125. // includeHidden can be the value true, or it can be a selector string
  1126. // indicating a special test; for example:
  1127. // $('#myForm').clearForm('.special:hidden')
  1128. // the above would clean hidden inputs that have the class of 'special'
  1129. if ((includeHidden === true && /hidden/.test(t)) ||
  1130. (typeof includeHidden === 'string' && $(this).is(includeHidden))) {
  1131. this.value = '';
  1132. }
  1133. }
  1134. });
  1135. };
  1136. /**
  1137. * Resets the form data or individual elements. Takes the following actions
  1138. * on the selected tags:
  1139. * - all fields within form elements will be reset to their original value
  1140. * - input / textarea / select fields will be reset to their original value
  1141. * - option / optgroup fields (for multi-selects) will defaulted individually
  1142. * - non-multiple options will find the right select to default
  1143. * - label elements will be searched against its 'for' attribute
  1144. * - all others will be searched for appropriate children to default
  1145. */
  1146. $.fn.resetForm = function() {
  1147. return this.each(function() {
  1148. var el = $(this);
  1149. var tag = this.tagName.toLowerCase();
  1150. switch (tag) {
  1151. case 'input':
  1152. this.checked = this.defaultChecked;
  1153. // fall through
  1154. case 'textarea':
  1155. this.value = this.defaultValue;
  1156. return true;
  1157. case 'option':
  1158. case 'optgroup':
  1159. var select = el.parents('select');
  1160. if (select.length && select[0].multiple) {
  1161. if (tag === 'option') {
  1162. this.selected = this.defaultSelected;
  1163. } else {
  1164. el.find('option').resetForm();
  1165. }
  1166. } else {
  1167. select.resetForm();
  1168. }
  1169. return true;
  1170. case 'select':
  1171. el.find('option').each(function(i) { // eslint-disable-line consistent-return
  1172. this.selected = this.defaultSelected;
  1173. if (this.defaultSelected && !el[0].multiple) {
  1174. el[0].selectedIndex = i;
  1175. return false;
  1176. }
  1177. });
  1178. return true;
  1179. case 'label':
  1180. var forEl = $(el.attr('for'));
  1181. var list = el.find('input,select,textarea');
  1182. if (forEl[0]) {
  1183. list.unshift(forEl[0]);
  1184. }
  1185. list.resetForm();
  1186. return true;
  1187. case 'form':
  1188. // guard against an input with the name of 'reset'
  1189. // note that IE reports the reset function as an 'object'
  1190. if (typeof this.reset === 'function' || (typeof this.reset === 'object' && !this.reset.nodeType)) {
  1191. this.reset();
  1192. }
  1193. return true;
  1194. default:
  1195. el.find('form,input,label,select,textarea').resetForm();
  1196. return true;
  1197. }
  1198. });
  1199. };
  1200. /**
  1201. * Enables or disables any matching elements.
  1202. */
  1203. $.fn.enable = function(b) {
  1204. if (typeof b === 'undefined') {
  1205. b = true;
  1206. }
  1207. return this.each(function() {
  1208. this.disabled = !b;
  1209. });
  1210. };
  1211. /**
  1212. * Checks/unchecks any matching checkboxes or radio buttons and
  1213. * selects/deselects and matching option elements.
  1214. */
  1215. $.fn.selected = function(select) {
  1216. if (typeof select === 'undefined') {
  1217. select = true;
  1218. }
  1219. return this.each(function() {
  1220. var t = this.type;
  1221. if (t === 'checkbox' || t === 'radio') {
  1222. this.checked = select;
  1223. } else if (this.tagName.toLowerCase() === 'option') {
  1224. var $sel = $(this).parent('select');
  1225. if (select && $sel[0] && $sel[0].type === 'select-one') {
  1226. // deselect all other options
  1227. $sel.find('option').selected(false);
  1228. }
  1229. this.selected = select;
  1230. }
  1231. });
  1232. };
  1233. // expose debug var
  1234. $.fn.ajaxSubmit.debug = false;
  1235. // helper fn for console logging
  1236. function log() {
  1237. if (!$.fn.ajaxSubmit.debug) {
  1238. return;
  1239. }
  1240. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments, '');
  1241. if (window.console && window.console.log) {
  1242. window.console.log(msg);
  1243. } else if (window.opera && window.opera.postError) {
  1244. window.opera.postError(msg);
  1245. }
  1246. }
  1247. }));