jquery.form.js 23 KB

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