jquery.form.js 41 KB

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