PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/jquery-validate/lib/jquery.form.js

#
JavaScript | 660 lines | 409 code | 67 blank | 184 comment | 216 complexity | 8c045afda4a843c9cba0c95eab46000d MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. /*
  2. * jQuery Form Plugin
  3. * version: 2.36 (07-NOV-2009)
  4. * @requires jQuery v1.2.6 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() {
  20. $(this).ajaxSubmit({
  21. target: '#output'
  22. });
  23. return false; // <-- important!
  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. var url = $.trim(this.attr('action'));
  49. if (url) {
  50. // clean url (don't include hash vaue)
  51. url = (url.match(/^([^#]+)/)||[])[1];
  52. }
  53. url = url || window.location.href || '';
  54. options = $.extend({
  55. url: url,
  56. type: this.attr('method') || 'GET',
  57. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  58. }, options || {});
  59. // hook for manipulating the form data before it is extracted;
  60. // convenient for use with rich editors like tinyMCE or FCKEditor
  61. var veto = {};
  62. this.trigger('form-pre-serialize', [this, options, veto]);
  63. if (veto.veto) {
  64. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  65. return this;
  66. }
  67. // provide opportunity to alter form data before it is serialized
  68. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  69. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  70. return this;
  71. }
  72. var a = this.formToArray(options.semantic);
  73. if (options.data) {
  74. options.extraData = options.data;
  75. for (var n in options.data) {
  76. if(options.data[n] instanceof Array) {
  77. for (var k in options.data[n])
  78. a.push( { name: n, value: options.data[n][k] } );
  79. }
  80. else
  81. a.push( { name: n, value: options.data[n] } );
  82. }
  83. }
  84. // give pre-submit callback an opportunity to abort the submit
  85. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  86. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  87. return this;
  88. }
  89. // fire vetoable 'validate' event
  90. this.trigger('form-submit-validate', [a, this, options, veto]);
  91. if (veto.veto) {
  92. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  93. return this;
  94. }
  95. var q = $.param(a);
  96. if (options.type.toUpperCase() == 'GET') {
  97. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  98. options.data = null; // data is null for 'get'
  99. }
  100. else
  101. options.data = q; // data is the query string for 'post'
  102. var $form = this, callbacks = [];
  103. if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
  104. if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
  105. // perform a load on the target only if dataType is not provided
  106. if (!options.dataType && options.target) {
  107. var oldSuccess = options.success || function(){};
  108. callbacks.push(function(data) {
  109. $(options.target).html(data).each(oldSuccess, arguments);
  110. });
  111. }
  112. else if (options.success)
  113. callbacks.push(options.success);
  114. options.success = function(data, status) {
  115. for (var i=0, max=callbacks.length; i < max; i++)
  116. callbacks[i].apply(options, [data, status, $form]);
  117. };
  118. // are there files to upload?
  119. var files = $('input:file', this).fieldValue();
  120. var found = false;
  121. for (var j=0; j < files.length; j++)
  122. if (files[j])
  123. found = true;
  124. var multipart = false;
  125. // var mp = 'multipart/form-data';
  126. // multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  127. // options.iframe allows user to force iframe mode
  128. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  129. if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
  130. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  131. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  132. if (options.closeKeepAlive)
  133. $.get(options.closeKeepAlive, fileUpload);
  134. else
  135. fileUpload();
  136. }
  137. else
  138. $.ajax(options);
  139. // fire 'notify' event
  140. this.trigger('form-submit-notify', [this, options]);
  141. return this;
  142. // private function for handling file uploads (hat tip to YAHOO!)
  143. function fileUpload() {
  144. var form = $form[0];
  145. if ($(':input[name=submit]', form).length) {
  146. alert('Error: Form elements must not be named "submit".');
  147. return;
  148. }
  149. var opts = $.extend({}, $.ajaxSettings, options);
  150. var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
  151. var id = 'jqFormIO' + (new Date().getTime());
  152. var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" />');
  153. var io = $io[0];
  154. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  155. var xhr = { // mock object
  156. aborted: 0,
  157. responseText: null,
  158. responseXML: null,
  159. status: 0,
  160. statusText: 'n/a',
  161. getAllResponseHeaders: function() {},
  162. getResponseHeader: function() {},
  163. setRequestHeader: function() {},
  164. abort: function() {
  165. this.aborted = 1;
  166. $io.attr('src', opts.iframeSrc); // abort op in progress
  167. }
  168. };
  169. var g = opts.global;
  170. // trigger ajax global events so that activity/block indicators work like normal
  171. if (g && ! $.active++) $.event.trigger("ajaxStart");
  172. if (g) $.event.trigger("ajaxSend", [xhr, opts]);
  173. if (s.beforeSend && s.beforeSend(xhr, s) === false) {
  174. s.global && $.active--;
  175. return;
  176. }
  177. if (xhr.aborted)
  178. return;
  179. var cbInvoked = 0;
  180. var timedOut = 0;
  181. // add submitting element to data if we know it
  182. var sub = form.clk;
  183. if (sub) {
  184. var n = sub.name;
  185. if (n && !sub.disabled) {
  186. options.extraData = options.extraData || {};
  187. options.extraData[n] = sub.value;
  188. if (sub.type == "image") {
  189. options.extraData[name+'.x'] = form.clk_x;
  190. options.extraData[name+'.y'] = form.clk_y;
  191. }
  192. }
  193. }
  194. // take a breath so that pending repaints get some cpu time before the upload starts
  195. setTimeout(function() {
  196. // make sure form attrs are set
  197. var t = $form.attr('target'), a = $form.attr('action');
  198. // update form attrs in IE friendly way
  199. form.setAttribute('target',id);
  200. if (form.getAttribute('method') != 'POST')
  201. form.setAttribute('method', 'POST');
  202. if (form.getAttribute('action') != opts.url)
  203. form.setAttribute('action', opts.url);
  204. // ie borks in some cases when setting encoding
  205. if (! options.skipEncodingOverride) {
  206. $form.attr({
  207. encoding: 'multipart/form-data',
  208. enctype: 'multipart/form-data'
  209. });
  210. }
  211. // support timout
  212. if (opts.timeout)
  213. setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
  214. // add "extra" data to form if provided in options
  215. var extraInputs = [];
  216. try {
  217. if (options.extraData)
  218. for (var n in options.extraData)
  219. extraInputs.push(
  220. $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
  221. .appendTo(form)[0]);
  222. // add iframe to doc and submit the form
  223. $io.appendTo('body');
  224. io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
  225. form.submit();
  226. }
  227. finally {
  228. // reset attrs and remove "extra" input elements
  229. form.setAttribute('action',a);
  230. t ? form.setAttribute('target', t) : $form.removeAttr('target');
  231. $(extraInputs).remove();
  232. }
  233. }, 10);
  234. var domCheckCount = 50;
  235. function cb() {
  236. if (cbInvoked++) return;
  237. io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
  238. var ok = true;
  239. try {
  240. if (timedOut) throw 'timeout';
  241. // extract the server response from the iframe
  242. var data, doc;
  243. doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
  244. var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  245. log('isXml='+isXml);
  246. if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
  247. if (--domCheckCount) {
  248. // in some browsers (Opera) the iframe DOM is not always traversable when
  249. // the onload callback fires, so we loop a bit to accommodate
  250. cbInvoked = 0;
  251. setTimeout(cb, 100);
  252. return;
  253. }
  254. log('Could not access iframe DOM after 50 tries.');
  255. return;
  256. }
  257. xhr.responseText = doc.body ? doc.body.innerHTML : null;
  258. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  259. xhr.getResponseHeader = function(header){
  260. var headers = {'content-type': opts.dataType};
  261. return headers[header];
  262. };
  263. if (opts.dataType == 'json' || opts.dataType == 'script') {
  264. // see if user embedded response in textarea
  265. var ta = doc.getElementsByTagName('textarea')[0];
  266. if (ta)
  267. xhr.responseText = ta.value;
  268. else {
  269. // account for browsers injecting pre around json response
  270. var pre = doc.getElementsByTagName('pre')[0];
  271. if (pre)
  272. xhr.responseText = pre.innerHTML;
  273. }
  274. }
  275. else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
  276. xhr.responseXML = toXml(xhr.responseText);
  277. }
  278. data = $.httpData(xhr, opts.dataType);
  279. }
  280. catch(e){
  281. ok = false;
  282. $.handleError(opts, xhr, 'error', e);
  283. }
  284. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  285. if (ok) {
  286. opts.success(data, 'success');
  287. if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
  288. }
  289. if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
  290. if (g && ! --$.active) $.event.trigger("ajaxStop");
  291. if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
  292. // clean up
  293. setTimeout(function() {
  294. $io.remove();
  295. xhr.responseXML = null;
  296. }, 100);
  297. };
  298. function toXml(s, doc) {
  299. if (window.ActiveXObject) {
  300. doc = new ActiveXObject('Microsoft.XMLDOM');
  301. doc.async = 'false';
  302. doc.loadXML(s);
  303. }
  304. else
  305. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  306. return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
  307. };
  308. };
  309. };
  310. /**
  311. * ajaxForm() provides a mechanism for fully automating form submission.
  312. *
  313. * The advantages of using this method instead of ajaxSubmit() are:
  314. *
  315. * 1: This method will include coordinates for <input type="image" /> elements (if the element
  316. * is used to submit the form).
  317. * 2. This method will include the submit element's name/value data (for the element that was
  318. * used to submit the form).
  319. * 3. This method binds the submit() method to the form for you.
  320. *
  321. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  322. * passes the options argument along after properly binding events for submit elements and
  323. * the form itself.
  324. */
  325. $.fn.ajaxForm = function(options) {
  326. return this.ajaxFormUnbind().bind('submit.form-plugin', function() {
  327. $(this).ajaxSubmit(options);
  328. return false;
  329. }).bind('click.form-plugin', function(e) {
  330. var target = e.target;
  331. var $el = $(target);
  332. if (!($el.is(":submit,input:image"))) {
  333. // is this a child element of the submit el? (ex: a span within a button)
  334. var t = $el.closest(':submit');
  335. if (t.length == 0)
  336. return;
  337. target = t[0];
  338. }
  339. var form = this;
  340. form.clk = target;
  341. if (target.type == 'image') {
  342. if (e.offsetX != undefined) {
  343. form.clk_x = e.offsetX;
  344. form.clk_y = e.offsetY;
  345. } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
  346. var offset = $el.offset();
  347. form.clk_x = e.pageX - offset.left;
  348. form.clk_y = e.pageY - offset.top;
  349. } else {
  350. form.clk_x = e.pageX - target.offsetLeft;
  351. form.clk_y = e.pageY - target.offsetTop;
  352. }
  353. }
  354. // clear form vars
  355. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  356. });
  357. };
  358. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  359. $.fn.ajaxFormUnbind = function() {
  360. return this.unbind('submit.form-plugin click.form-plugin');
  361. };
  362. /**
  363. * formToArray() gathers form element data into an array of objects that can
  364. * be passed to any of the following ajax functions: $.get, $.post, or load.
  365. * Each object in the array has both a 'name' and 'value' property. An example of
  366. * an array for a simple login form might be:
  367. *
  368. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  369. *
  370. * It is this array that is passed to pre-submit callback functions provided to the
  371. * ajaxSubmit() and ajaxForm() methods.
  372. */
  373. $.fn.formToArray = function(semantic) {
  374. var a = [];
  375. if (this.length == 0) return a;
  376. var form = this[0];
  377. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  378. if (!els) return a;
  379. for(var i=0, max=els.length; i < max; i++) {
  380. var el = els[i];
  381. var n = el.name;
  382. if (!n) continue;
  383. if (semantic && form.clk && el.type == "image") {
  384. // handle image inputs on the fly when semantic == true
  385. if(!el.disabled && form.clk == el) {
  386. a.push({name: n, value: $(el).val()});
  387. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  388. }
  389. continue;
  390. }
  391. var v = $.fieldValue(el, true);
  392. if (v && v.constructor == Array) {
  393. for(var j=0, jmax=v.length; j < jmax; j++)
  394. a.push({name: n, value: v[j]});
  395. }
  396. else if (v !== null && typeof v != 'undefined')
  397. a.push({name: n, value: v});
  398. }
  399. if (!semantic && form.clk) {
  400. // input type=='image' are not found in elements array! handle it here
  401. var $input = $(form.clk), input = $input[0], n = input.name;
  402. if (n && !input.disabled && input.type == 'image') {
  403. a.push({name: n, value: $input.val()});
  404. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  405. }
  406. }
  407. return a;
  408. };
  409. /**
  410. * Serializes form data into a 'submittable' string. This method will return a string
  411. * in the format: name1=value1&amp;name2=value2
  412. */
  413. $.fn.formSerialize = function(semantic) {
  414. //hand off to jQuery.param for proper encoding
  415. return $.param(this.formToArray(semantic));
  416. };
  417. /**
  418. * Serializes all field elements in the jQuery object into a query string.
  419. * This method will return a string in the format: name1=value1&amp;name2=value2
  420. */
  421. $.fn.fieldSerialize = function(successful) {
  422. var a = [];
  423. this.each(function() {
  424. var n = this.name;
  425. if (!n) return;
  426. var v = $.fieldValue(this, successful);
  427. if (v && v.constructor == Array) {
  428. for (var i=0,max=v.length; i < max; i++)
  429. a.push({name: n, value: v[i]});
  430. }
  431. else if (v !== null && typeof v != 'undefined')
  432. a.push({name: this.name, value: v});
  433. });
  434. //hand off to jQuery.param for proper encoding
  435. return $.param(a);
  436. };
  437. /**
  438. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  439. *
  440. * <form><fieldset>
  441. * <input name="A" type="text" />
  442. * <input name="A" type="text" />
  443. * <input name="B" type="checkbox" value="B1" />
  444. * <input name="B" type="checkbox" value="B2"/>
  445. * <input name="C" type="radio" value="C1" />
  446. * <input name="C" type="radio" value="C2" />
  447. * </fieldset></form>
  448. *
  449. * var v = $(':text').fieldValue();
  450. * // if no values are entered into the text inputs
  451. * v == ['','']
  452. * // if values entered into the text inputs are 'foo' and 'bar'
  453. * v == ['foo','bar']
  454. *
  455. * var v = $(':checkbox').fieldValue();
  456. * // if neither checkbox is checked
  457. * v === undefined
  458. * // if both checkboxes are checked
  459. * v == ['B1', 'B2']
  460. *
  461. * var v = $(':radio').fieldValue();
  462. * // if neither radio is checked
  463. * v === undefined
  464. * // if first radio is checked
  465. * v == ['C1']
  466. *
  467. * The successful argument controls whether or not the field element must be 'successful'
  468. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  469. * The default value of the successful argument is true. If this value is false the value(s)
  470. * for each element is returned.
  471. *
  472. * Note: This method *always* returns an array. If no valid value can be determined the
  473. * array will be empty, otherwise it will contain one or more values.
  474. */
  475. $.fn.fieldValue = function(successful) {
  476. for (var val=[], i=0, max=this.length; i < max; i++) {
  477. var el = this[i];
  478. var v = $.fieldValue(el, successful);
  479. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
  480. continue;
  481. v.constructor == Array ? $.merge(val, v) : val.push(v);
  482. }
  483. return val;
  484. };
  485. /**
  486. * Returns the value of the field element.
  487. */
  488. $.fieldValue = function(el, successful) {
  489. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  490. if (typeof successful == 'undefined') successful = true;
  491. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  492. (t == 'checkbox' || t == 'radio') && !el.checked ||
  493. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  494. tag == 'select' && el.selectedIndex == -1))
  495. return null;
  496. if (tag == 'select') {
  497. var index = el.selectedIndex;
  498. if (index < 0) return null;
  499. var a = [], ops = el.options;
  500. var one = (t == 'select-one');
  501. var max = (one ? index+1 : ops.length);
  502. for(var i=(one ? index : 0); i < max; i++) {
  503. var op = ops[i];
  504. if (op.selected) {
  505. var v = op.value;
  506. if (!v) // extra pain for IE...
  507. v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
  508. if (one) return v;
  509. a.push(v);
  510. }
  511. }
  512. return a;
  513. }
  514. return el.value;
  515. };
  516. /**
  517. * Clears the form data. Takes the following actions on the form's input fields:
  518. * - input text fields will have their 'value' property set to the empty string
  519. * - select elements will have their 'selectedIndex' property set to -1
  520. * - checkbox and radio inputs will have their 'checked' property set to false
  521. * - inputs of type submit, button, reset, and hidden will *not* be effected
  522. * - button elements will *not* be effected
  523. */
  524. $.fn.clearForm = function() {
  525. return this.each(function() {
  526. $('input,select,textarea', this).clearFields();
  527. });
  528. };
  529. /**
  530. * Clears the selected form elements.
  531. */
  532. $.fn.clearFields = $.fn.clearInputs = function() {
  533. return this.each(function() {
  534. var t = this.type, tag = this.tagName.toLowerCase();
  535. if (t == 'text' || t == 'password' || tag == 'textarea')
  536. this.value = '';
  537. else if (t == 'checkbox' || t == 'radio')
  538. this.checked = false;
  539. else if (tag == 'select')
  540. this.selectedIndex = -1;
  541. });
  542. };
  543. /**
  544. * Resets the form data. Causes all form elements to be reset to their original value.
  545. */
  546. $.fn.resetForm = function() {
  547. return this.each(function() {
  548. // guard against an input with the name of 'reset'
  549. // note that IE reports the reset function as an 'object'
  550. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
  551. this.reset();
  552. });
  553. };
  554. /**
  555. * Enables or disables any matching elements.
  556. */
  557. $.fn.enable = function(b) {
  558. if (b == undefined) b = true;
  559. return this.each(function() {
  560. this.disabled = !b;
  561. });
  562. };
  563. /**
  564. * Checks/unchecks any matching checkboxes or radio buttons and
  565. * selects/deselects and matching option elements.
  566. */
  567. $.fn.selected = function(select) {
  568. if (select == undefined) select = true;
  569. return this.each(function() {
  570. var t = this.type;
  571. if (t == 'checkbox' || t == 'radio')
  572. this.checked = select;
  573. else if (this.tagName.toLowerCase() == 'option') {
  574. var $sel = $(this).parent('select');
  575. if (select && $sel[0] && $sel[0].type == 'select-one') {
  576. // deselect all other options
  577. $sel.find('option').selected(false);
  578. }
  579. this.selected = select;
  580. }
  581. });
  582. };
  583. // helper fn for console logging
  584. // set $.fn.ajaxSubmit.debug to true to enable debug logging
  585. function log() {
  586. if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
  587. window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
  588. };
  589. })(jQuery);