f792d24_jquery.form-2.14_8.js 28KB

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