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. log('isXml='+isXml);
  317. if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
  318. if (--domCheckCount) {
  319. // in some browsers (Opera) the iframe DOM is not always traversable when
  320. // the onload callback fires, so we loop a bit to accommodate
  321. log('requeing onLoad callback, DOM not available');
  322. setTimeout(cb, 250);
  323. return;
  324. }
  325. // let this fall through because server response could be an empty document
  326. //log('Could not access iframe DOM after mutiple tries.');
  327. //throw 'DOMException: not available';
  328. }
  329. //log('response detected');
  330. var docRoot = doc.body ? doc.body : doc.documentElement;
  331. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  332. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  333. if (isXml)
  334. s.dataType = 'xml';
  335. xhr.getResponseHeader = function(header){
  336. var headers = {'content-type': s.dataType};
  337. return headers[header];
  338. };
  339. // support for XHR 'status' & 'statusText' emulation :
  340. if (docRoot) {
  341. xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
  342. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  343. }
  344. var dt = s.dataType || '';
  345. var scr = /(json|script|text)/.test(dt.toLowerCase());
  346. if (scr || s.textarea) {
  347. // see if user embedded response in textarea
  348. var ta = doc.getElementsByTagName('textarea')[0];
  349. if (ta) {
  350. xhr.responseText = ta.value;
  351. // support for XHR 'status' & 'statusText' emulation :
  352. xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
  353. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  354. }
  355. else if (scr) {
  356. // account for browsers injecting pre around json response
  357. var pre = doc.getElementsByTagName('pre')[0];
  358. var b = doc.getElementsByTagName('body')[0];
  359. if (pre) {
  360. xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML;
  361. }
  362. else if (b) {
  363. xhr.responseText = b.innerHTML;
  364. }
  365. }
  366. }
  367. else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
  368. xhr.responseXML = toXml(xhr.responseText);
  369. }
  370. try {
  371. data = httpData(xhr, s.dataType, s);
  372. }
  373. catch (e) {
  374. status = 'parsererror';
  375. xhr.error = errMsg = (e || status);
  376. }
  377. }
  378. catch (e) {
  379. log('error caught',e);
  380. status = 'error';
  381. xhr.error = errMsg = (e || status);
  382. }
  383. if (xhr.aborted) {
  384. log('upload aborted');
  385. status = null;
  386. }
  387. if (xhr.status) { // we've set xhr.status
  388. status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
  389. }
  390. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  391. if (status === 'success') {
  392. s.success && s.success.call(s.context, data, 'success', xhr);
  393. g && $.event.trigger("ajaxSuccess", [xhr, s]);
  394. }
  395. else if (status) {
  396. if (errMsg == undefined)
  397. errMsg = xhr.statusText;
  398. s.error && s.error.call(s.context, xhr, status, errMsg);
  399. g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
  400. }
  401. g && $.event.trigger("ajaxComplete", [xhr, s]);
  402. if (g && ! --$.active) {
  403. $.event.trigger("ajaxStop");
  404. }
  405. s.complete && s.complete.call(s.context, xhr, status);
  406. callbackProcessed = true;
  407. if (s.timeout)
  408. clearTimeout(timeoutHandle);
  409. // clean up
  410. setTimeout(function() {
  411. if (!s.iframeTarget)
  412. $io.remove();
  413. xhr.responseXML = null;
  414. }, 100);
  415. }
  416. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  417. if (window.ActiveXObject) {
  418. doc = new ActiveXObject('Microsoft.XMLDOM');
  419. doc.async = 'false';
  420. doc.loadXML(s);
  421. }
  422. else {
  423. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  424. }
  425. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  426. };
  427. var parseJSON = $.parseJSON || function(s) {
  428. return window['eval']('(' + s + ')');
  429. };
  430. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  431. var ct = xhr.getResponseHeader('content-type') || '',
  432. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  433. data = xml ? xhr.responseXML : xhr.responseText;
  434. if (xml && data.documentElement.nodeName === 'parsererror') {
  435. $.error && $.error('parsererror');
  436. }
  437. if (s && s.dataFilter) {
  438. data = s.dataFilter(data, type);
  439. }
  440. if (typeof data === 'string') {
  441. if (type === 'json' || !type && ct.indexOf('json') >= 0) {
  442. data = parseJSON(data);
  443. } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
  444. $.globalEval(data);
  445. }
  446. }
  447. return data;
  448. };
  449. }
  450. };
  451. /**
  452. * ajaxForm() provides a mechanism for fully automating form submission.
  453. *
  454. * The advantages of using this method instead of ajaxSubmit() are:
  455. *
  456. * 1: This method will include coordinates for <input type="image" /> elements (if the element
  457. * is used to submit the form).
  458. * 2. This method will include the submit element's name/value data (for the element that was
  459. * used to submit the form).
  460. * 3. This method binds the submit() method to the form for you.
  461. *
  462. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  463. * passes the options argument along after properly binding events for submit elements and
  464. * the form itself.
  465. */
  466. $.fn.ajaxForm = function(options) {
  467. // in jQuery 1.3+ we can fix mistakes with the ready state
  468. if (this.length === 0) {
  469. var o = { s: this.selector, c: this.context };
  470. if (!$.isReady && o.s) {
  471. log('DOM not ready, queuing ajaxForm');
  472. $(function() {
  473. $(o.s,o.c).ajaxForm(options);
  474. });
  475. return this;
  476. }
  477. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  478. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  479. return this;
  480. }
  481. return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
  482. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  483. e.preventDefault();
  484. $(this).ajaxSubmit(options);
  485. }
  486. }).bind('click.form-plugin', function(e) {
  487. var target = e.target;
  488. var $el = $(target);
  489. if (!($el.is(":submit,input:image"))) {
  490. // is this a child element of the submit el? (ex: a span within a button)
  491. var t = $el.closest(':submit');
  492. if (t.length == 0) {
  493. return;
  494. }
  495. target = t[0];
  496. }
  497. var form = this;
  498. form.clk = target;
  499. if (target.type == 'image') {
  500. if (e.offsetX != undefined) {
  501. form.clk_x = e.offsetX;
  502. form.clk_y = e.offsetY;
  503. } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
  504. var offset = $el.offset();
  505. form.clk_x = e.pageX - offset.left;
  506. form.clk_y = e.pageY - offset.top;
  507. } else {
  508. form.clk_x = e.pageX - target.offsetLeft;
  509. form.clk_y = e.pageY - target.offsetTop;
  510. }
  511. }
  512. // clear form vars
  513. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  514. });
  515. };
  516. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  517. $.fn.ajaxFormUnbind = function() {
  518. return this.unbind('submit.form-plugin click.form-plugin');
  519. };
  520. /**
  521. * formToArray() gathers form element data into an array of objects that can
  522. * be passed to any of the following ajax functions: $.get, $.post, or load.
  523. * Each object in the array has both a 'name' and 'value' property. An example of
  524. * an array for a simple login form might be:
  525. *
  526. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  527. *
  528. * It is this array that is passed to pre-submit callback functions provided to the
  529. * ajaxSubmit() and ajaxForm() methods.
  530. */
  531. $.fn.formToArray = function(semantic) {
  532. var a = [];
  533. if (this.length === 0) {
  534. return a;
  535. }
  536. var form = this[0];
  537. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  538. if (!els) {
  539. return a;
  540. }
  541. var i,j,n,v,el,max,jmax;
  542. for(i=0, max=els.length; i < max; i++) {
  543. el = els[i];
  544. n = el.name;
  545. if (!n) {
  546. continue;
  547. }
  548. if (semantic && form.clk && el.type == "image") {
  549. // handle image inputs on the fly when semantic == true
  550. if(!el.disabled && form.clk == el) {
  551. a.push({name: n, value: $(el).val()});
  552. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  553. }
  554. continue;
  555. }
  556. v = $.fieldValue(el, true);
  557. if (v && v.constructor == Array) {
  558. for(j=0, jmax=v.length; j < jmax; j++) {
  559. a.push({name: n, value: v[j]});
  560. }
  561. }
  562. else if (v !== null && typeof v != 'undefined') {
  563. a.push({name: n, value: v});
  564. }
  565. }
  566. if (!semantic && form.clk) {
  567. // input type=='image' are not found in elements array! handle it here
  568. var $input = $(form.clk), input = $input[0];
  569. n = input.name;
  570. if (n && !input.disabled && input.type == 'image') {
  571. a.push({name: n, value: $input.val()});
  572. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  573. }
  574. }
  575. return a;
  576. };
  577. /**
  578. * Serializes form data into a 'submittable' string. This method will return a string
  579. * in the format: name1=value1&amp;name2=value2
  580. */
  581. $.fn.formSerialize = function(semantic) {
  582. //hand off to jQuery.param for proper encoding
  583. return $.param(this.formToArray(semantic));
  584. };
  585. /**
  586. * Serializes all field elements in the jQuery object into a query string.
  587. * This method will return a string in the format: name1=value1&amp;name2=value2
  588. */
  589. $.fn.fieldSerialize = function(successful) {
  590. var a = [];
  591. this.each(function() {
  592. var n = this.name;
  593. if (!n) {
  594. return;
  595. }
  596. var v = $.fieldValue(this, successful);
  597. if (v && v.constructor == Array) {
  598. for (var i=0,max=v.length; i < max; i++) {
  599. a.push({name: n, value: v[i]});
  600. }
  601. }
  602. else if (v !== null && typeof v != 'undefined') {
  603. a.push({name: this.name, value: v});
  604. }
  605. });
  606. //hand off to jQuery.param for proper encoding
  607. return $.param(a);
  608. };
  609. /**
  610. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  611. *
  612. * <form><fieldset>
  613. * <input name="A" type="text" />
  614. * <input name="A" type="text" />
  615. * <input name="B" type="checkbox" value="B1" />
  616. * <input name="B" type="checkbox" value="B2"/>
  617. * <input name="C" type="radio" value="C1" />
  618. * <input name="C" type="radio" value="C2" />
  619. * </fieldset></form>
  620. *
  621. * var v = $(':text').fieldValue();
  622. * // if no values are entered into the text inputs
  623. * v == ['','']
  624. * // if values entered into the text inputs are 'foo' and 'bar'
  625. * v == ['foo','bar']
  626. *
  627. * var v = $(':checkbox').fieldValue();
  628. * // if neither checkbox is checked
  629. * v === undefined
  630. * // if both checkboxes are checked
  631. * v == ['B1', 'B2']
  632. *
  633. * var v = $(':radio').fieldValue();
  634. * // if neither radio is checked
  635. * v === undefined
  636. * // if first radio is checked
  637. * v == ['C1']
  638. *
  639. * The successful argument controls whether or not the field element must be 'successful'
  640. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  641. * The default value of the successful argument is true. If this value is false the value(s)
  642. * for each element is returned.
  643. *
  644. * Note: This method *always* returns an array. If no valid value can be determined the
  645. * array will be empty, otherwise it will contain one or more values.
  646. */
  647. $.fn.fieldValue = function(successful) {
  648. for (var val=[], i=0, max=this.length; i < max; i++) {
  649. var el = this[i];
  650. var v = $.fieldValue(el, successful);
  651. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
  652. continue;
  653. }
  654. v.constructor == Array ? $.merge(val, v) : val.push(v);
  655. }
  656. return val;
  657. };
  658. /**
  659. * Returns the value of the field element.
  660. */
  661. $.fieldValue = function(el, successful) {
  662. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  663. if (successful === undefined) {
  664. successful = true;
  665. }
  666. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  667. (t == 'checkbox' || t == 'radio') && !el.checked ||
  668. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  669. tag == 'select' && el.selectedIndex == -1)) {
  670. return null;
  671. }
  672. if (tag == 'select') {
  673. var index = el.selectedIndex;
  674. if (index < 0) {
  675. return null;
  676. }
  677. var a = [], ops = el.options;
  678. var one = (t == 'select-one');
  679. var max = (one ? index+1 : ops.length);
  680. for(var i=(one ? index : 0); i < max; i++) {
  681. var op = ops[i];
  682. if (op.selected) {
  683. var v = op.value;
  684. if (!v) { // extra pain for IE...
  685. v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
  686. }
  687. if (one) {
  688. return v;
  689. }
  690. a.push(v);
  691. }
  692. }
  693. return a;
  694. }
  695. return $(el).val();
  696. };
  697. /**
  698. * Clears the form data. Takes the following actions on the form's input fields:
  699. * - input text fields will have their 'value' property set to the empty string
  700. * - select elements will have their 'selectedIndex' property set to -1
  701. * - checkbox and radio inputs will have their 'checked' property set to false
  702. * - inputs of type submit, button, reset, and hidden will *not* be effected
  703. * - button elements will *not* be effected
  704. */
  705. $.fn.clearForm = function() {
  706. return this.each(function() {
  707. $('input,select,textarea', this).clearFields();
  708. });
  709. };
  710. /**
  711. * Clears the selected form elements.
  712. */
  713. $.fn.clearFields = $.fn.clearInputs = function() {
  714. return this.each(function() {
  715. var t = this.type, tag = this.tagName.toLowerCase();
  716. if (t == 'text' || t == 'password' || tag == 'textarea') {
  717. this.value = '';
  718. }
  719. else if (t == 'checkbox' || t == 'radio') {
  720. this.checked = false;
  721. }
  722. else if (tag == 'select') {
  723. this.selectedIndex = -1;
  724. }
  725. });
  726. };
  727. /**
  728. * Resets the form data. Causes all form elements to be reset to their original value.
  729. */
  730. $.fn.resetForm = function() {
  731. return this.each(function() {
  732. // guard against an input with the name of 'reset'
  733. // note that IE reports the reset function as an 'object'
  734. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
  735. this.reset();
  736. }
  737. });
  738. };
  739. /**
  740. * Enables or disables any matching elements.
  741. */
  742. $.fn.enable = function(b) {
  743. if (b === undefined) {
  744. b = true;
  745. }
  746. return this.each(function() {
  747. this.disabled = !b;
  748. });
  749. };
  750. /**
  751. * Checks/unchecks any matching checkboxes or radio buttons and
  752. * selects/deselects and matching option elements.
  753. */
  754. $.fn.selected = function(select) {
  755. if (select === undefined) {
  756. select = true;
  757. }
  758. return this.each(function() {
  759. var t = this.type;
  760. if (t == 'checkbox' || t == 'radio') {
  761. this.checked = select;
  762. }
  763. else if (this.tagName.toLowerCase() == 'option') {
  764. var $sel = $(this).parent('select');
  765. if (select && $sel[0] && $sel[0].type == 'select-one') {
  766. // deselect all other options
  767. $sel.find('option').selected(false);
  768. }
  769. this.selected = select;
  770. }
  771. });
  772. };
  773. // helper fn for console logging
  774. function log() {
  775. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
  776. if (window.console && window.console.log) {
  777. window.console.log(msg);
  778. }
  779. else if (window.opera && window.opera.postError) {
  780. window.opera.postError(msg);
  781. }
  782. };
  783. })(jQuery);