jquery.form.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. /*!
  2. * jQuery Form Plugin
  3. * version: 2.64 (25-FEB-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. type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57)
  59. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  60. }, options);
  61. // hook for manipulating the form data before it is extracted;
  62. // convenient for use with rich editors like tinyMCE or FCKEditor
  63. var veto = {};
  64. this.trigger('form-pre-serialize', [this, options, veto]);
  65. if (veto.veto) {
  66. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  67. return this;
  68. }
  69. // provide opportunity to alter form data before it is serialized
  70. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  71. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  72. return this;
  73. }
  74. var n,v,a = this.formToArray(options.semantic);
  75. if (options.data) {
  76. options.extraData = options.data;
  77. for (n in options.data) {
  78. if(options.data[n] instanceof Array) {
  79. for (var k in options.data[n]) {
  80. a.push( { name: n, value: options.data[n][k] } );
  81. }
  82. }
  83. else {
  84. v = options.data[n];
  85. v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
  86. a.push( { name: n, value: v } );
  87. }
  88. }
  89. }
  90. // give pre-submit callback an opportunity to abort the submit
  91. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  92. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  93. return this;
  94. }
  95. // fire vetoable 'validate' event
  96. this.trigger('form-submit-validate', [a, this, options, veto]);
  97. if (veto.veto) {
  98. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  99. return this;
  100. }
  101. var q = $.param(a);
  102. if (options.type.toUpperCase() == 'GET') {
  103. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  104. options.data = null; // data is null for 'get'
  105. }
  106. else {
  107. options.data = q; // data is the query string for 'post'
  108. }
  109. var $form = this, callbacks = [];
  110. if (options.resetForm) {
  111. callbacks.push(function() { $form.resetForm(); });
  112. }
  113. if (options.clearForm) {
  114. callbacks.push(function() { $form.clearForm(); });
  115. }
  116. // perform a load on the target only if dataType is not provided
  117. if (!options.dataType && options.target) {
  118. var oldSuccess = options.success || function(){};
  119. callbacks.push(function(data) {
  120. var fn = options.replaceTarget ? 'replaceWith' : 'html';
  121. $(options.target)[fn](data).each(oldSuccess, arguments);
  122. });
  123. }
  124. else if (options.success) {
  125. callbacks.push(options.success);
  126. }
  127. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  128. var context = options.context || options; // jQuery 1.4+ supports scope context
  129. for (var i=0, max=callbacks.length; i < max; i++) {
  130. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  131. }
  132. };
  133. // are there files to upload?
  134. var fileInputs = $('input:file', this).length > 0;
  135. var mp = 'multipart/form-data';
  136. var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  137. // options.iframe allows user to force iframe mode
  138. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  139. if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
  140. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  141. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  142. if (options.closeKeepAlive) {
  143. $.get(options.closeKeepAlive, fileUpload);
  144. }
  145. else {
  146. fileUpload();
  147. }
  148. }
  149. else {
  150. $.ajax(options);
  151. }
  152. // fire 'notify' event
  153. this.trigger('form-submit-notify', [this, options]);
  154. return this;
  155. // private function for handling file uploads (hat tip to YAHOO!)
  156. function fileUpload() {
  157. var form = $form[0];
  158. if ($(':input[name=submit],:input[id=submit]', form).length) {
  159. // if there is an input with a name or id of 'submit' then we won't be
  160. // able to invoke the submit fn on the form (at least not x-browser)
  161. alert('Error: Form elements must not have name or id of "submit".');
  162. return;
  163. }
  164. var s = $.extend(true, {}, $.ajaxSettings, options);
  165. s.context = s.context || s;
  166. var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id;
  167. var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />');
  168. var io = $io[0];
  169. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  170. var xhr = { // mock object
  171. aborted: 0,
  172. responseText: null,
  173. responseXML: null,
  174. status: 0,
  175. statusText: 'n/a',
  176. getAllResponseHeaders: function() {},
  177. getResponseHeader: function() {},
  178. setRequestHeader: function() {},
  179. abort: function() {
  180. this.aborted = 1;
  181. $io.attr('src', s.iframeSrc); // abort op in progress
  182. }
  183. };
  184. var g = s.global;
  185. // trigger ajax global events so that activity/block indicators work like normal
  186. if (g && ! $.active++) {
  187. $.event.trigger("ajaxStart");
  188. }
  189. if (g) {
  190. $.event.trigger("ajaxSend", [xhr, s]);
  191. }
  192. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  193. if (s.global) {
  194. $.active--;
  195. }
  196. return;
  197. }
  198. if (xhr.aborted) {
  199. return;
  200. }
  201. var timedOut = 0;
  202. // add submitting element to data if we know it
  203. var sub = form.clk;
  204. if (sub) {
  205. var n = sub.name;
  206. if (n && !sub.disabled) {
  207. s.extraData = s.extraData || {};
  208. s.extraData[n] = sub.value;
  209. if (sub.type == "image") {
  210. s.extraData[n+'.x'] = form.clk_x;
  211. s.extraData[n+'.y'] = form.clk_y;
  212. }
  213. }
  214. }
  215. // take a breath so that pending repaints get some cpu time before the upload starts
  216. function doSubmit() {
  217. // make sure form attrs are set
  218. var t = $form.attr('target'), a = $form.attr('action');
  219. // update form attrs in IE friendly way
  220. form.setAttribute('target',id);
  221. if (form.getAttribute('method') != 'POST') {
  222. form.setAttribute('method', 'POST');
  223. }
  224. if (form.getAttribute('action') != s.url) {
  225. form.setAttribute('action', s.url);
  226. }
  227. // ie borks in some cases when setting encoding
  228. if (! s.skipEncodingOverride) {
  229. $form.attr({
  230. encoding: 'multipart/form-data',
  231. enctype: 'multipart/form-data'
  232. });
  233. }
  234. // support timout
  235. if (s.timeout) {
  236. setTimeout(function() { timedOut = true; cb(); }, s.timeout);
  237. }
  238. // add "extra" data to form if provided in options
  239. var extraInputs = [];
  240. try {
  241. if (s.extraData) {
  242. for (var n in s.extraData) {
  243. extraInputs.push(
  244. $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
  245. .appendTo(form)[0]);
  246. }
  247. }
  248. // add iframe to doc and submit the form
  249. $io.appendTo('body');
  250. io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
  251. form.submit();
  252. }
  253. finally {
  254. // reset attrs and remove "extra" input elements
  255. form.setAttribute('action',a);
  256. if(t) {
  257. form.setAttribute('target', t);
  258. } else {
  259. $form.removeAttr('target');
  260. }
  261. $(extraInputs).remove();
  262. }
  263. }
  264. if (s.forceSync) {
  265. doSubmit();
  266. }
  267. else {
  268. setTimeout(doSubmit, 10); // this lets dom updates render
  269. }
  270. var data, doc, domCheckCount = 50;
  271. function cb() {
  272. doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
  273. if (!doc || doc.location.href == s.iframeSrc) {
  274. // response not received yet
  275. return;
  276. }
  277. io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
  278. var ok = true;
  279. try {
  280. if (timedOut) {
  281. throw 'timeout';
  282. }
  283. var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  284. log('isXml='+isXml);
  285. if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
  286. if (--domCheckCount) {
  287. // in some browsers (Opera) the iframe DOM is not always traversable when
  288. // the onload callback fires, so we loop a bit to accommodate
  289. log('requeing onLoad callback, DOM not available');
  290. setTimeout(cb, 250);
  291. return;
  292. }
  293. // let this fall through because server response could be an empty document
  294. //log('Could not access iframe DOM after mutiple tries.');
  295. //throw 'DOMException: not available';
  296. }
  297. //log('response detected');
  298. xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null;
  299. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  300. xhr.getResponseHeader = function(header){
  301. var headers = {'content-type': s.dataType};
  302. return headers[header];
  303. };
  304. var scr = /(json|script)/.test(s.dataType);
  305. if (scr || s.textarea) {
  306. // see if user embedded response in textarea
  307. var ta = doc.getElementsByTagName('textarea')[0];
  308. if (ta) {
  309. xhr.responseText = ta.value;
  310. }
  311. else if (scr) {
  312. // account for browsers injecting pre around json response
  313. var pre = doc.getElementsByTagName('pre')[0];
  314. var b = doc.getElementsByTagName('body')[0];
  315. if (pre) {
  316. xhr.responseText = pre.textContent;
  317. }
  318. else if (b) {
  319. xhr.responseText = b.innerHTML;
  320. }
  321. }
  322. }
  323. else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
  324. xhr.responseXML = toXml(xhr.responseText);
  325. }
  326. data = httpData(xhr, s.dataType, s);
  327. }
  328. catch(e){
  329. log('error caught:',e);
  330. ok = false;
  331. xhr.error = e;
  332. s.error && s.error.call(s.context, xhr, 'error', e);
  333. g && $.event.trigger("ajaxError", [xhr, s, e]);
  334. }
  335. if (xhr.aborted) {
  336. log('upload aborted');
  337. ok = false;
  338. }
  339. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  340. if (ok) {
  341. s.success && s.success.call(s.context, data, 'success', xhr);
  342. g && $.event.trigger("ajaxSuccess", [xhr, s]);
  343. }
  344. g && $.event.trigger("ajaxComplete", [xhr, s]);
  345. if (g && ! --$.active) {
  346. $.event.trigger("ajaxStop");
  347. }
  348. s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error');
  349. // clean up
  350. setTimeout(function() {
  351. $io.removeData('form-plugin-onload');
  352. $io.remove();
  353. xhr.responseXML = null;
  354. }, 100);
  355. }
  356. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  357. if (window.ActiveXObject) {
  358. doc = new ActiveXObject('Microsoft.XMLDOM');
  359. doc.async = 'false';
  360. doc.loadXML(s);
  361. }
  362. else {
  363. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  364. }
  365. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  366. };
  367. var parseJSON = $.parseJSON || function(s) {
  368. return window['eval']('(' + s + ')');
  369. };
  370. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  371. var ct = xhr.getResponseHeader('content-type') || '',
  372. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  373. data = xml ? xhr.responseXML : xhr.responseText;
  374. if (xml && data.documentElement.nodeName === 'parsererror') {
  375. $.error && $.error('parsererror');
  376. }
  377. if (s && s.dataFilter) {
  378. data = s.dataFilter(data, type);
  379. }
  380. if (typeof data === 'string') {
  381. // -- custom hack to make the ajax request works with non typed dataType
  382. // author : Thomas Rabaix <thomas.rabaix@sonata-project.org>
  383. // account for browsers injecting pre around json response
  384. var matches = xhr.responseText.match(/^(<pre([^>]*)>|<body([^>]*)>)(.*)(<\/pre>|<\/body>)$/);
  385. if(matches && matches.length == 6){
  386. xhr.responseText = matches[4];
  387. }
  388. if(xhr.responseText[0] == '{') {
  389. data = parseJSON(xhr.responseText);
  390. }
  391. // -- end custom hack
  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);