jquery.form.js 20 KB

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