jquery.form.js 25 KB

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