jquery.form.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /*!
  2. * jQuery Form Plugin
  3. * version: 2.96 (16-FEB-2012)
  4. * @requires jQuery v1.3.2 or later
  5. *
  6. * Examples and documentation at: http://malsup.com/jquery/form/
  7. * Dual licensed under the MIT and GPL licenses:
  8. * http://www.opensource.org/licenses/mit-license.php
  9. * http://www.gnu.org/licenses/gpl.html
  10. */
  11. ;(function($) {
  12. /*
  13. Usage Note:
  14. -----------
  15. Do not use both ajaxSubmit and ajaxForm on the same form. These
  16. functions are mutually exclusive. Use ajaxSubmit if you want
  17. to bind your own submit handler to the form. For example,
  18. $(document).ready(function() {
  19. $('#myForm').bind('submit', function(e) {
  20. e.preventDefault(); // <-- important
  21. $(this).ajaxSubmit({
  22. target: '#output'
  23. });
  24. });
  25. });
  26. Use ajaxForm when you want the plugin to manage all the event binding
  27. for you. For example,
  28. $(document).ready(function() {
  29. $('#myForm').ajaxForm({
  30. target: '#output'
  31. });
  32. });
  33. You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
  34. form does not have to exist when you invoke ajaxForm:
  35. $('#myForm').ajaxForm({
  36. delegation: true,
  37. target: '#output'
  38. });
  39. When using ajaxForm, the ajaxSubmit function will be invoked for you
  40. at the appropriate time.
  41. */
  42. /**
  43. * ajaxSubmit() provides a mechanism for immediately submitting
  44. * an HTML form using AJAX.
  45. */
  46. $.fn.ajaxSubmit = function(options) {
  47. // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
  48. if (!this.length) {
  49. log('ajaxSubmit: skipping submit process - no element selected');
  50. return this;
  51. }
  52. var method, action, url, $form = this;
  53. if (typeof options == 'function') {
  54. options = { success: options };
  55. }
  56. method = this.attr('method');
  57. action = this.attr('action');
  58. url = (typeof action === 'string') ? $.trim(action) : '';
  59. url = url || window.location.href || '';
  60. if (url) {
  61. // clean url (don't include hash vaue)
  62. url = (url.match(/^([^#]+)/)||[])[1];
  63. }
  64. options = $.extend(true, {
  65. url: url,
  66. success: $.ajaxSettings.success,
  67. type: method || 'GET',
  68. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  69. }, options);
  70. // hook for manipulating the form data before it is extracted;
  71. // convenient for use with rich editors like tinyMCE or FCKEditor
  72. var veto = {};
  73. this.trigger('form-pre-serialize', [this, options, veto]);
  74. if (veto.veto) {
  75. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  76. return this;
  77. }
  78. // provide opportunity to alter form data before it is serialized
  79. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  80. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  81. return this;
  82. }
  83. var traditional = options.traditional;
  84. if ( traditional === undefined ) {
  85. traditional = $.ajaxSettings.traditional;
  86. }
  87. var qx,n,v,a = this.formToArray(options.semantic);
  88. if (options.data) {
  89. options.extraData = options.data;
  90. qx = $.param(options.data, traditional);
  91. }
  92. // give pre-submit callback an opportunity to abort the submit
  93. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  94. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  95. return this;
  96. }
  97. // fire vetoable 'validate' event
  98. this.trigger('form-submit-validate', [a, this, options, veto]);
  99. if (veto.veto) {
  100. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  101. return this;
  102. }
  103. var q = $.param(a, traditional);
  104. if (qx) {
  105. q = ( q ? (q + '&' + qx) : qx );
  106. }
  107. if (options.type.toUpperCase() == 'GET') {
  108. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  109. options.data = null; // data is null for 'get'
  110. }
  111. else {
  112. options.data = q; // data is the query string for 'post'
  113. }
  114. var callbacks = [];
  115. if (options.resetForm) {
  116. callbacks.push(function() { $form.resetForm(); });
  117. }
  118. if (options.clearForm) {
  119. callbacks.push(function() { $form.clearForm(options.includeHidden); });
  120. }
  121. // perform a load on the target only if dataType is not provided
  122. if (!options.dataType && options.target) {
  123. var oldSuccess = options.success || function(){};
  124. callbacks.push(function(data) {
  125. var fn = options.replaceTarget ? 'replaceWith' : 'html';
  126. $(options.target)[fn](data).each(oldSuccess, arguments);
  127. });
  128. }
  129. else if (options.success) {
  130. callbacks.push(options.success);
  131. }
  132. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  133. var context = options.context || options; // jQuery 1.4+ supports scope context
  134. for (var i=0, max=callbacks.length; i < max; i++) {
  135. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  136. }
  137. };
  138. // are there files to upload?
  139. var fileInputs = $('input:file:enabled[value]', this); // [value] (issue #113)
  140. var hasFileInputs = fileInputs.length > 0;
  141. var mp = 'multipart/form-data';
  142. var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  143. var fileAPI = !!(hasFileInputs && fileInputs.get(0).files && window.FormData);
  144. log("fileAPI :" + fileAPI);
  145. var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
  146. // options.iframe allows user to force iframe mode
  147. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  148. if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
  149. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  150. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  151. if (options.closeKeepAlive) {
  152. $.get(options.closeKeepAlive, function() {
  153. fileUploadIframe(a);
  154. });
  155. }
  156. else {
  157. fileUploadIframe(a);
  158. }
  159. }
  160. else if ((hasFileInputs || multipart) && fileAPI) {
  161. options.progress = options.progress || $.noop;
  162. fileUploadXhr(a);
  163. }
  164. else {
  165. $.ajax(options);
  166. }
  167. // fire 'notify' event
  168. this.trigger('form-submit-notify', [this, options]);
  169. return this;
  170. // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
  171. function fileUploadXhr(a) {
  172. var formdata = new FormData();
  173. for (var i=0; i < a.length; i++) {
  174. if (a[i].type == 'file')
  175. continue;
  176. formdata.append(a[i].name, a[i].value);
  177. }
  178. $form.find('input:file:enabled').each(function(){
  179. var name = $(this).attr('name'), files = this.files;
  180. if (name) {
  181. for (var i=0; i < files.length; i++)
  182. formdata.append(name, files[i]);
  183. }
  184. });
  185. if (options.extraData) {
  186. for (var k in options.extraData)
  187. formdata.append(k, options.extraData[k])
  188. }
  189. options.data = null;
  190. var s = $.extend(true, {}, $.ajaxSettings, options, {
  191. contentType: false,
  192. processData: false,
  193. cache: false,
  194. type: 'POST'
  195. });
  196. //s.context = s.context || s;
  197. s.data = null;
  198. var beforeSend = s.beforeSend;
  199. s.beforeSend = function(xhr, o) {
  200. o.data = formdata;
  201. if(xhr.upload) { // unfortunately, jQuery doesn't expose this prop (http://bugs.jquery.com/ticket/10190)
  202. xhr.upload.onprogress = function(event) {
  203. o.progress(event.position, event.total);
  204. };
  205. }
  206. if(beforeSend)
  207. beforeSend.call(o, xhr, options);
  208. };
  209. $.ajax(s);
  210. }
  211. // private function for handling file uploads (hat tip to YAHOO!)
  212. function fileUploadIframe(a) {
  213. var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
  214. var useProp = !!$.fn.prop;
  215. if (a) {
  216. if ( useProp ) {
  217. // ensure that every serialized input is still enabled
  218. for (i=0; i < a.length; i++) {
  219. el = $(form[a[i].name]);
  220. el.prop('disabled', false);
  221. }
  222. } else {
  223. for (i=0; i < a.length; i++) {
  224. el = $(form[a[i].name]);
  225. el.removeAttr('disabled');
  226. }
  227. };
  228. }
  229. if ($(':input[name=submit],:input[id=submit]', form).length) {
  230. // if there is an input with a name or id of 'submit' then we won't be
  231. // able to invoke the submit fn on the form (at least not x-browser)
  232. alert('Error: Form elements must not have name or id of "submit".');
  233. return;
  234. }
  235. s = $.extend(true, {}, $.ajaxSettings, options);
  236. s.context = s.context || s;
  237. id = 'jqFormIO' + (new Date().getTime());
  238. if (s.iframeTarget) {
  239. $io = $(s.iframeTarget);
  240. n = $io.attr('name');
  241. if (n == null)
  242. $io.attr('name', id);
  243. else
  244. id = n;
  245. }
  246. else {
  247. $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
  248. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  249. }
  250. io = $io[0];
  251. xhr = { // mock object
  252. aborted: 0,
  253. responseText: null,
  254. responseXML: null,
  255. status: 0,
  256. statusText: 'n/a',
  257. getAllResponseHeaders: function() {},
  258. getResponseHeader: function() {},
  259. setRequestHeader: function() {},
  260. abort: function(status) {
  261. var e = (status === 'timeout' ? 'timeout' : 'aborted');
  262. log('aborting upload... ' + e);
  263. this.aborted = 1;
  264. $io.attr('src', s.iframeSrc); // abort op in progress
  265. xhr.error = e;
  266. s.error && s.error.call(s.context, xhr, e, status);
  267. g && $.event.trigger("ajaxError", [xhr, s, e]);
  268. s.complete && s.complete.call(s.context, xhr, e);
  269. }
  270. };
  271. g = s.global;
  272. // trigger ajax global events so that activity/block indicators work like normal
  273. if (g && ! $.active++) {
  274. $.event.trigger("ajaxStart");
  275. }
  276. if (g) {
  277. $.event.trigger("ajaxSend", [xhr, s]);
  278. }
  279. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  280. if (s.global) {
  281. $.active--;
  282. }
  283. return;
  284. }
  285. if (xhr.aborted) {
  286. return;
  287. }
  288. // add submitting element to data if we know it
  289. sub = form.clk;
  290. if (sub) {
  291. n = sub.name;
  292. if (n && !sub.disabled) {
  293. s.extraData = s.extraData || {};
  294. s.extraData[n] = sub.value;
  295. if (sub.type == "image") {
  296. s.extraData[n+'.x'] = form.clk_x;
  297. s.extraData[n+'.y'] = form.clk_y;
  298. }
  299. }
  300. }
  301. var CLIENT_TIMEOUT_ABORT = 1;
  302. var SERVER_ABORT = 2;
  303. function getDoc(frame) {
  304. var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
  305. return doc;
  306. }
  307. // Rails CSRF hack (thanks to Yvan Barthelemy)
  308. var csrf_token = $('meta[name=csrf-token]').attr('content');
  309. var csrf_param = $('meta[name=csrf-param]').attr('content');
  310. if (csrf_param && csrf_token) {
  311. s.extraData = s.extraData || {};
  312. s.extraData[csrf_param] = csrf_token;
  313. }
  314. // take a breath so that pending repaints get some cpu time before the upload starts
  315. function doSubmit() {
  316. // make sure form attrs are set
  317. var t = $form.attr('target'), a = $form.attr('action');
  318. // update form attrs in IE friendly way
  319. form.setAttribute('target',id);
  320. if (!method) {
  321. form.setAttribute('method', 'POST');
  322. }
  323. if (a != s.url) {
  324. form.setAttribute('action', s.url);
  325. }
  326. // ie borks in some cases when setting encoding
  327. if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
  328. $form.attr({
  329. encoding: 'multipart/form-data',
  330. enctype: 'multipart/form-data'
  331. });
  332. }
  333. // support timout
  334. if (s.timeout) {
  335. timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
  336. }
  337. // look for server aborts
  338. function checkState() {
  339. try {
  340. var state = getDoc(io).readyState;
  341. log('state = ' + state);
  342. if (state.toLowerCase() == 'uninitialized')
  343. setTimeout(checkState,50);
  344. }
  345. catch(e) {
  346. log('Server abort: ' , e, ' (', e.name, ')');
  347. cb(SERVER_ABORT);
  348. timeoutHandle && clearTimeout(timeoutHandle);
  349. timeoutHandle = undefined;
  350. }
  351. }
  352. // add "extra" data to form if provided in options
  353. var extraInputs = [];
  354. try {
  355. if (s.extraData) {
  356. for (var n in s.extraData) {
  357. extraInputs.push(
  358. $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
  359. .appendTo(form)[0]);
  360. }
  361. }
  362. if (!s.iframeTarget) {
  363. // add iframe to doc and submit the form
  364. $io.appendTo('body');
  365. io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
  366. }
  367. setTimeout(checkState,15);
  368. form.submit();
  369. }
  370. finally {
  371. // reset attrs and remove "extra" input elements
  372. form.setAttribute('action',a);
  373. if(t) {
  374. form.setAttribute('target', t);
  375. } else {
  376. $form.removeAttr('target');
  377. }
  378. $(extraInputs).remove();
  379. }
  380. }
  381. if (s.forceSync) {
  382. doSubmit();
  383. }
  384. else {
  385. setTimeout(doSubmit, 10); // this lets dom updates render
  386. }
  387. var data, doc, domCheckCount = 50, callbackProcessed;
  388. function cb(e) {
  389. if (xhr.aborted || callbackProcessed) {
  390. return;
  391. }
  392. try {
  393. doc = getDoc(io);
  394. }
  395. catch(ex) {
  396. log('cannot access response document: ', ex);
  397. e = SERVER_ABORT;
  398. }
  399. if (e === CLIENT_TIMEOUT_ABORT && xhr) {
  400. xhr.abort('timeout');
  401. return;
  402. }
  403. else if (e == SERVER_ABORT && xhr) {
  404. xhr.abort('server abort');
  405. return;
  406. }
  407. if (!doc || doc.location.href == s.iframeSrc) {
  408. // response not received yet
  409. if (!timedOut)
  410. return;
  411. }
  412. io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
  413. var status = 'success', errMsg;
  414. try {
  415. if (timedOut) {
  416. throw 'timeout';
  417. }
  418. var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  419. log('isXml='+isXml);
  420. if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
  421. if (--domCheckCount) {
  422. // in some browsers (Opera) the iframe DOM is not always traversable when
  423. // the onload callback fires, so we loop a bit to accommodate
  424. log('requeing onLoad callback, DOM not available');
  425. setTimeout(cb, 250);
  426. return;
  427. }
  428. // let this fall through because server response could be an empty document
  429. //log('Could not access iframe DOM after mutiple tries.');
  430. //throw 'DOMException: not available';
  431. }
  432. //log('response detected');
  433. var docRoot = doc.body ? doc.body : doc.documentElement;
  434. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  435. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  436. if (isXml)
  437. s.dataType = 'xml';
  438. xhr.getResponseHeader = function(header){
  439. var headers = {'content-type': s.dataType};
  440. return headers[header];
  441. };
  442. // support for XHR 'status' & 'statusText' emulation :
  443. if (docRoot) {
  444. xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
  445. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  446. }
  447. var dt = (s.dataType || '').toLowerCase();
  448. var scr = /(json|script|text)/.test(dt);
  449. if (scr || s.textarea) {
  450. // see if user embedded response in textarea
  451. var ta = doc.getElementsByTagName('textarea')[0];
  452. if (ta) {
  453. xhr.responseText = ta.value;
  454. // support for XHR 'status' & 'statusText' emulation :
  455. xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
  456. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  457. }
  458. else if (scr) {
  459. // account for browsers injecting pre around json response
  460. var pre = doc.getElementsByTagName('pre')[0];
  461. var b = doc.getElementsByTagName('body')[0];
  462. if (pre) {
  463. xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
  464. }
  465. else if (b) {
  466. xhr.responseText = b.textContent ? b.textContent : b.innerText;
  467. }
  468. }
  469. }
  470. else if (dt == 'xml' && !xhr.responseXML && xhr.responseText != null) {
  471. xhr.responseXML = toXml(xhr.responseText);
  472. }
  473. try {
  474. data = httpData(xhr, dt, s);
  475. }
  476. catch (e) {
  477. status = 'parsererror';
  478. xhr.error = errMsg = (e || status);
  479. }
  480. }
  481. catch (e) {
  482. log('error caught: ',e);
  483. status = 'error';
  484. xhr.error = errMsg = (e || status);
  485. }
  486. if (xhr.aborted) {
  487. log('upload aborted');
  488. status = null;
  489. }
  490. if (xhr.status) { // we've set xhr.status
  491. status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
  492. }
  493. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  494. if (status === 'success') {
  495. s.success && s.success.call(s.context, data, 'success', xhr);
  496. g && $.event.trigger("ajaxSuccess", [xhr, s]);
  497. }
  498. else if (status) {
  499. if (errMsg == undefined)
  500. errMsg = xhr.statusText;
  501. s.error && s.error.call(s.context, xhr, status, errMsg);
  502. g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
  503. }
  504. g && $.event.trigger("ajaxComplete", [xhr, s]);
  505. if (g && ! --$.active) {
  506. $.event.trigger("ajaxStop");
  507. }
  508. s.complete && s.complete.call(s.context, xhr, status);
  509. callbackProcessed = true;
  510. if (s.timeout)
  511. clearTimeout(timeoutHandle);
  512. // clean up
  513. setTimeout(function() {
  514. if (!s.iframeTarget)
  515. $io.remove();
  516. xhr.responseXML = null;
  517. }, 100);
  518. }
  519. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  520. if (window.ActiveXObject) {
  521. doc = new ActiveXObject('Microsoft.XMLDOM');
  522. doc.async = 'false';
  523. doc.loadXML(s);
  524. }
  525. else {
  526. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  527. }
  528. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  529. };
  530. var parseJSON = $.parseJSON || function(s) {
  531. return window['eval']('(' + s + ')');
  532. };
  533. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  534. var ct = xhr.getResponseHeader('content-type') || '',
  535. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  536. data = xml ? xhr.responseXML : xhr.responseText;
  537. if (xml && data.documentElement.nodeName === 'parsererror') {
  538. $.error && $.error('parsererror');
  539. }
  540. if (s && s.dataFilter) {
  541. data = s.dataFilter(data, type);
  542. }
  543. if (typeof data === 'string') {
  544. if (type === 'json' || !type && ct.indexOf('json') >= 0) {
  545. data = parseJSON(data);
  546. } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
  547. $.globalEval(data);
  548. }
  549. }
  550. return data;
  551. };
  552. }
  553. };
  554. /**
  555. * ajaxForm() provides a mechanism for fully automating form submission.
  556. *
  557. * The advantages of using this method instead of ajaxSubmit() are:
  558. *
  559. * 1: This method will include coordinates for <input type="image" /> elements (if the element
  560. * is used to submit the form).
  561. * 2. This method will include the submit element's name/value data (for the element that was
  562. * used to submit the form).
  563. * 3. This method binds the submit() method to the form for you.
  564. *
  565. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  566. * passes the options argument along after properly binding events for submit elements and
  567. * the form itself.
  568. */
  569. $.fn.ajaxForm = function(options) {
  570. options = options || {};
  571. options.delegation = options.delegation && $.isFunction($.fn.on);
  572. // in jQuery 1.3+ we can fix mistakes with the ready state
  573. if (!options.delegation && this.length === 0) {
  574. var o = { s: this.selector, c: this.context };
  575. if (!$.isReady && o.s) {
  576. log('DOM not ready, queuing ajaxForm');
  577. $(function() {
  578. $(o.s,o.c).ajaxForm(options);
  579. });
  580. return this;
  581. }
  582. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  583. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  584. return this;
  585. }
  586. if ( options.delegation ) {
  587. $(document)
  588. .off('submit.form-plugin', this.selector, doAjaxSubmit)
  589. .off('click.form-plugin', this.selector, captureSubmittingElement)
  590. .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
  591. .on('click.form-plugin', this.selector, options, captureSubmittingElement);
  592. return this;
  593. }
  594. return this.ajaxFormUnbind()
  595. .bind('submit.form-plugin', options, doAjaxSubmit)
  596. .bind('click.form-plugin', options, captureSubmittingElement);
  597. };
  598. // private event handlers
  599. function doAjaxSubmit(e) {
  600. var options = e.data;
  601. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  602. e.preventDefault();
  603. $(this).ajaxSubmit(options);
  604. }
  605. }
  606. function captureSubmittingElement(e) {
  607. var target = e.target;
  608. var $el = $(target);
  609. if (!($el.is(":submit,input:image"))) {
  610. // is this a child element of the submit el? (ex: a span within a button)
  611. var t = $el.closest(':submit');
  612. if (t.length == 0) {
  613. return;
  614. }
  615. target = t[0];
  616. }
  617. var form = this;
  618. form.clk = target;
  619. if (target.type == 'image') {
  620. if (e.offsetX != undefined) {
  621. form.clk_x = e.offsetX;
  622. form.clk_y = e.offsetY;
  623. } else if (typeof $.fn.offset == 'function') {
  624. var offset = $el.offset();
  625. form.clk_x = e.pageX - offset.left;
  626. form.clk_y = e.pageY - offset.top;
  627. } else {
  628. form.clk_x = e.pageX - target.offsetLeft;
  629. form.clk_y = e.pageY - target.offsetTop;
  630. }
  631. }
  632. // clear form vars
  633. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  634. };
  635. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  636. $.fn.ajaxFormUnbind = function() {
  637. return this.unbind('submit.form-plugin click.form-plugin');
  638. };
  639. /**
  640. * formToArray() gathers form element data into an array of objects that can
  641. * be passed to any of the following ajax functions: $.get, $.post, or load.
  642. * Each object in the array has both a 'name' and 'value' property. An example of
  643. * an array for a simple login form might be:
  644. *
  645. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  646. *
  647. * It is this array that is passed to pre-submit callback functions provided to the
  648. * ajaxSubmit() and ajaxForm() methods.
  649. */
  650. $.fn.formToArray = function(semantic) {
  651. var a = [];
  652. if (this.length === 0) {
  653. return a;
  654. }
  655. var form = this[0];
  656. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  657. if (!els) {
  658. return a;
  659. }
  660. var i,j,n,v,el,max,jmax;
  661. for(i=0, max=els.length; i < max; i++) {
  662. el = els[i];
  663. n = el.name;
  664. if (!n) {
  665. continue;
  666. }
  667. if (semantic && form.clk && el.type == "image") {
  668. // handle image inputs on the fly when semantic == true
  669. if(!el.disabled && form.clk == el) {
  670. a.push({name: n, value: $(el).val(), type: el.type });
  671. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  672. }
  673. continue;
  674. }
  675. v = $.fieldValue(el, true);
  676. if (v && v.constructor == Array) {
  677. for(j=0, jmax=v.length; j < jmax; j++) {
  678. a.push({name: n, value: v[j]});
  679. }
  680. }
  681. else if (v !== null && typeof v != 'undefined') {
  682. a.push({name: n, value: v, type: el.type});
  683. }
  684. }
  685. if (!semantic && form.clk) {
  686. // input type=='image' are not found in elements array! handle it here
  687. var $input = $(form.clk), input = $input[0];
  688. n = input.name;
  689. if (n && !input.disabled && input.type == 'image') {
  690. a.push({name: n, value: $input.val()});
  691. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  692. }
  693. }
  694. return a;
  695. };
  696. /**
  697. * Serializes form data into a 'submittable' string. This method will return a string
  698. * in the format: name1=value1&amp;name2=value2
  699. */
  700. $.fn.formSerialize = function(semantic) {
  701. //hand off to jQuery.param for proper encoding
  702. return $.param(this.formToArray(semantic));
  703. };
  704. /**
  705. * Serializes all field elements in the jQuery object into a query string.
  706. * This method will return a string in the format: name1=value1&amp;name2=value2
  707. */
  708. $.fn.fieldSerialize = function(successful) {
  709. var a = [];
  710. this.each(function() {
  711. var n = this.name;
  712. if (!n) {
  713. return;
  714. }
  715. var v = $.fieldValue(this, successful);
  716. if (v && v.constructor == Array) {
  717. for (var i=0,max=v.length; i < max; i++) {
  718. a.push({name: n, value: v[i]});
  719. }
  720. }
  721. else if (v !== null && typeof v != 'undefined') {
  722. a.push({name: this.name, value: v});
  723. }
  724. });
  725. //hand off to jQuery.param for proper encoding
  726. return $.param(a);
  727. };
  728. /**
  729. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  730. *
  731. * <form><fieldset>
  732. * <input name="A" type="text" />
  733. * <input name="A" type="text" />
  734. * <input name="B" type="checkbox" value="B1" />
  735. * <input name="B" type="checkbox" value="B2"/>
  736. * <input name="C" type="radio" value="C1" />
  737. * <input name="C" type="radio" value="C2" />
  738. * </fieldset></form>
  739. *
  740. * var v = $(':text').fieldValue();
  741. * // if no values are entered into the text inputs
  742. * v == ['','']
  743. * // if values entered into the text inputs are 'foo' and 'bar'
  744. * v == ['foo','bar']
  745. *
  746. * var v = $(':checkbox').fieldValue();
  747. * // if neither checkbox is checked
  748. * v === undefined
  749. * // if both checkboxes are checked
  750. * v == ['B1', 'B2']
  751. *
  752. * var v = $(':radio').fieldValue();
  753. * // if neither radio is checked
  754. * v === undefined
  755. * // if first radio is checked
  756. * v == ['C1']
  757. *
  758. * The successful argument controls whether or not the field element must be 'successful'
  759. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  760. * The default value of the successful argument is true. If this value is false the value(s)
  761. * for each element is returned.
  762. *
  763. * Note: This method *always* returns an array. If no valid value can be determined the
  764. * array will be empty, otherwise it will contain one or more values.
  765. */
  766. $.fn.fieldValue = function(successful) {
  767. for (var val=[], i=0, max=this.length; i < max; i++) {
  768. var el = this[i];
  769. var v = $.fieldValue(el, successful);
  770. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
  771. continue;
  772. }
  773. v.constructor == Array ? $.merge(val, v) : val.push(v);
  774. }
  775. return val;
  776. };
  777. /**
  778. * Returns the value of the field element.
  779. */
  780. $.fieldValue = function(el, successful) {
  781. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  782. if (successful === undefined) {
  783. successful = true;
  784. }
  785. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  786. (t == 'checkbox' || t == 'radio') && !el.checked ||
  787. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  788. tag == 'select' && el.selectedIndex == -1)) {
  789. return null;
  790. }
  791. if (tag == 'select') {
  792. var index = el.selectedIndex;
  793. if (index < 0) {
  794. return null;
  795. }
  796. var a = [], ops = el.options;
  797. var one = (t == 'select-one');
  798. var max = (one ? index+1 : ops.length);
  799. for(var i=(one ? index : 0); i < max; i++) {
  800. var op = ops[i];
  801. if (op.selected) {
  802. var v = op.value;
  803. if (!v) { // extra pain for IE...
  804. v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
  805. }
  806. if (one) {
  807. return v;
  808. }
  809. a.push(v);
  810. }
  811. }
  812. return a;
  813. }
  814. return $(el).val();
  815. };
  816. /**
  817. * Clears the form data. Takes the following actions on the form's input fields:
  818. * - input text fields will have their 'value' property set to the empty string
  819. * - select elements will have their 'selectedIndex' property set to -1
  820. * - checkbox and radio inputs will have their 'checked' property set to false
  821. * - inputs of type submit, button, reset, and hidden will *not* be effected
  822. * - button elements will *not* be effected
  823. */
  824. $.fn.clearForm = function(includeHidden) {
  825. return this.each(function() {
  826. $('input,select,textarea', this).clearFields(includeHidden);
  827. });
  828. };
  829. /**
  830. * Clears the selected form elements.
  831. */
  832. $.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
  833. var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
  834. return this.each(function() {
  835. var t = this.type, tag = this.tagName.toLowerCase();
  836. if (re.test(t) || tag == 'textarea' || (includeHidden && /hidden/.test(t)) ) {
  837. this.value = '';
  838. }
  839. else if (t == 'checkbox' || t == 'radio') {
  840. this.checked = false;
  841. }
  842. else if (tag == 'select') {
  843. this.selectedIndex = -1;
  844. }
  845. });
  846. };
  847. /**
  848. * Resets the form data. Causes all form elements to be reset to their original value.
  849. */
  850. $.fn.resetForm = function() {
  851. return this.each(function() {
  852. // guard against an input with the name of 'reset'
  853. // note that IE reports the reset function as an 'object'
  854. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
  855. this.reset();
  856. }
  857. });
  858. };
  859. /**
  860. * Enables or disables any matching elements.
  861. */
  862. $.fn.enable = function(b) {
  863. if (b === undefined) {
  864. b = true;
  865. }
  866. return this.each(function() {
  867. this.disabled = !b;
  868. });
  869. };
  870. /**
  871. * Checks/unchecks any matching checkboxes or radio buttons and
  872. * selects/deselects and matching option elements.
  873. */
  874. $.fn.selected = function(select) {
  875. if (select === undefined) {
  876. select = true;
  877. }
  878. return this.each(function() {
  879. var t = this.type;
  880. if (t == 'checkbox' || t == 'radio') {
  881. this.checked = select;
  882. }
  883. else if (this.tagName.toLowerCase() == 'option') {
  884. var $sel = $(this).parent('select');
  885. if (select && $sel[0] && $sel[0].type == 'select-one') {
  886. // deselect all other options
  887. $sel.find('option').selected(false);
  888. }
  889. this.selected = select;
  890. }
  891. });
  892. };
  893. // expose debug var
  894. $.fn.ajaxSubmit.debug = false;
  895. // helper fn for console logging
  896. function log() {
  897. if (!$.fn.ajaxSubmit.debug)
  898. return;
  899. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
  900. if (window.console && window.console.log) {
  901. window.console.log(msg);
  902. }
  903. else if (window.opera && window.opera.postError) {
  904. window.opera.postError(msg);
  905. }
  906. };
  907. })(jQuery);