3 * version: 2.12 (06/07/2008)
\r
4 * @requires jQuery v1.2.2 or later
\r
6 * Examples and documentation at: http://malsup.com/jquery/form/
\r
7 * Dual licensed under the MIT and GPL licenses:
\r
8 * http://www.opensource.org/licenses/mit-license.php
\r
9 * http://www.gnu.org/licenses/gpl.html
\r
18 Do not use both ajaxSubmit and ajaxForm on the same form. These
\r
19 functions are intended to be exclusive. Use ajaxSubmit if you want
\r
20 to bind your own submit handler to the form. For example,
\r
22 $(document).ready(function() {
\r
23 $('#myForm').bind('submit', function() {
\r
24 $(this).ajaxSubmit({
\r
27 return false; // <-- important!
\r
31 Use ajaxForm when you want the plugin to manage all the event binding
\r
32 for you. For example,
\r
34 $(document).ready(function() {
\r
35 $('#myForm').ajaxForm({
\r
40 When using ajaxForm, the ajaxSubmit function will be invoked for you
\r
41 at the appropriate time.
\r
45 * ajaxSubmit() provides a mechanism for immediately submitting
\r
46 * an HTML form using AJAX.
\r
48 $.fn.ajaxSubmit = function(options) {
\r
49 // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
\r
51 log('ajaxSubmit: skipping submit process - no element selected');
\r
55 if (typeof options == 'function')
\r
56 options = { success: options };
\r
58 options = $.extend({
\r
59 url: this.attr('action') || window.location.toString(),
\r
60 type: this.attr('method') || 'GET'
\r
63 // hook for manipulating the form data before it is extracted;
\r
64 // convenient for use with rich editors like tinyMCE or FCKEditor
\r
66 this.trigger('form-pre-serialize', [this, options, veto]);
\r
68 log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
\r
72 var a = this.formToArray(options.semantic);
\r
74 options.extraData = options.data;
\r
75 for (var n in options.data)
\r
76 a.push( { name: n, value: options.data[n] } );
\r
79 // give pre-submit callback an opportunity to abort the submit
\r
80 if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
\r
81 log('ajaxSubmit: submit aborted via beforeSubmit callback');
\r
85 // fire vetoable 'validate' event
\r
86 this.trigger('form-submit-validate', [a, this, options, veto]);
\r
88 log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
\r
94 if (options.type.toUpperCase() == 'GET') {
\r
95 options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
\r
96 options.data = null; // data is null for 'get'
\r
99 options.data = q; // data is the query string for 'post'
\r
101 var $form = this, callbacks = [];
\r
102 if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
\r
103 if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
\r
105 // perform a load on the target only if dataType is not provided
\r
106 if (!options.dataType && options.target) {
\r
107 var oldSuccess = options.success || function(){};
\r
108 callbacks.push(function(data) {
\r
109 $(options.target).html(data).each(oldSuccess, arguments);
\r
112 else if (options.success)
\r
113 callbacks.push(options.success);
\r
115 options.success = function(data, status) {
\r
116 for (var i=0, max=callbacks.length; i < max; i++)
\r
117 callbacks[i](data, status, $form);
\r
120 // are there files to upload?
\r
121 var files = $('input:file', this).fieldValue();
\r
123 for (var j=0; j < files.length; j++)
\r
127 // options.iframe allows user to force iframe mode
\r
128 if (options.iframe || found) {
\r
129 // hack to fix Safari hang (thanks to Tim Molendijk for this)
\r
130 // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
\r
131 if ($.browser.safari && options.closeKeepAlive)
\r
132 $.get(options.closeKeepAlive, fileUpload);
\r
139 // fire 'notify' event
\r
140 this.trigger('form-submit-notify', [this, options]);
\r
144 // private function for handling file uploads (hat tip to YAHOO!)
\r
145 function fileUpload() {
\r
146 var form = $form[0];
\r
148 if ($(':input[@name=submit]', form).length) {
\r
149 alert('Error: Form elements must not be named "submit".');
\r
153 var opts = $.extend({}, $.ajaxSettings, options);
\r
155 var id = 'jqFormIO' + (new Date().getTime());
\r
156 var $io = $('<iframe id="' + id + '" name="' + id + '" />');
\r
159 if ($.browser.msie || $.browser.opera)
\r
160 io.src = 'javascript:false;document.write("");';
\r
161 $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
\r
163 var xhr = { // mock object
\r
164 responseText: null,
\r
168 getAllResponseHeaders: function() {},
\r
169 getResponseHeader: function() {},
\r
170 setRequestHeader: function() {}
\r
173 var g = opts.global;
\r
174 // trigger ajax global events so that activity/block indicators work like normal
\r
175 if (g && ! $.active++) $.event.trigger("ajaxStart");
\r
176 if (g) $.event.trigger("ajaxSend", [xhr, opts]);
\r
181 // add submitting element to data if we know it
\r
182 var sub = form.clk;
\r
185 if (n && !sub.disabled) {
\r
186 options.extraData = options.extraData || {};
\r
187 options.extraData[n] = sub.value;
\r
188 if (sub.type == "image") {
\r
189 options.extraData[name+'.x'] = form.clk_x;
\r
190 options.extraData[name+'.y'] = form.clk_y;
\r
195 // take a breath so that pending repaints get some cpu time before the upload starts
\r
196 setTimeout(function() {
\r
197 // make sure form attrs are set
\r
198 var t = $form.attr('target'), a = $form.attr('action');
\r
201 encoding: 'multipart/form-data',
\r
202 enctype: 'multipart/form-data',
\r
209 setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
\r
211 // add "extra" data to form if provided in options
\r
212 var extraInputs = [];
\r
214 if (options.extraData)
\r
215 for (var n in options.extraData)
\r
217 $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
\r
218 .appendTo(form)[0]);
\r
220 // add iframe to doc and submit the form
\r
221 $io.appendTo('body');
\r
222 io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
\r
226 // reset attrs and remove "extra" input elements
\r
227 $form.attr('action', a);
\r
228 t ? $form.attr('target', t) : $form.removeAttr('target');
\r
229 $(extraInputs).remove();
\r
234 if (cbInvoked++) return;
\r
236 io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
\r
241 if (timedOut) throw 'timeout';
\r
242 // extract the server response from the iframe
\r
245 doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
\r
247 if (doc.body == null && !operaHack && $.browser.opera) {
\r
248 // In Opera 9.2.x the iframe DOM is not always traversable when
\r
249 // the onload callback fires so we give Opera 100ms to right itself
\r
252 setTimeout(cb, 100);
\r
256 xhr.responseText = doc.body ? doc.body.innerHTML : null;
\r
257 xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
\r
258 xhr.getResponseHeader = function(header){
\r
259 var headers = {'content-type': opts.dataType};
\r
260 return headers[header];
\r
263 if (opts.dataType == 'json' || opts.dataType == 'script') {
\r
264 var ta = doc.getElementsByTagName('textarea')[0];
\r
265 xhr.responseText = ta ? ta.value : xhr.responseText;
\r
267 else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
\r
268 xhr.responseXML = toXml(xhr.responseText);
\r
270 data = $.httpData(xhr, opts.dataType);
\r
274 $.handleError(opts, xhr, 'error', e);
\r
277 // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
\r
279 opts.success(data, 'success');
\r
280 if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
\r
282 if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
\r
283 if (g && ! --$.active) $.event.trigger("ajaxStop");
\r
284 if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
\r
287 setTimeout(function() {
\r
289 xhr.responseXML = null;
\r
293 function toXml(s, doc) {
\r
294 if (window.ActiveXObject) {
\r
295 doc = new ActiveXObject('Microsoft.XMLDOM');
\r
296 doc.async = 'false';
\r
300 doc = (new DOMParser()).parseFromString(s, 'text/xml');
\r
301 return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
\r
307 * ajaxForm() provides a mechanism for fully automating form submission.
\r
309 * The advantages of using this method instead of ajaxSubmit() are:
\r
311 * 1: This method will include coordinates for <input type="image" /> elements (if the element
\r
312 * is used to submit the form).
\r
313 * 2. This method will include the submit element's name/value data (for the element that was
\r
314 * used to submit the form).
\r
315 * 3. This method binds the submit() method to the form for you.
\r
317 * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
\r
318 * passes the options argument along after properly binding events for submit elements and
\r
321 $.fn.ajaxForm = function(options) {
\r
322 return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
\r
323 $(this).ajaxSubmit(options);
\r
325 }).each(function() {
\r
326 // store options in hash
\r
327 $(":submit,input:image", this).bind('click.form-plugin',function(e) {
\r
328 var $form = this.form;
\r
330 if (this.type == 'image') {
\r
331 if (e.offsetX != undefined) {
\r
332 $form.clk_x = e.offsetX;
\r
333 $form.clk_y = e.offsetY;
\r
334 } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
\r
335 var offset = $(this).offset();
\r
336 $form.clk_x = e.pageX - offset.left;
\r
337 $form.clk_y = e.pageY - offset.top;
\r
339 $form.clk_x = e.pageX - this.offsetLeft;
\r
340 $form.clk_y = e.pageY - this.offsetTop;
\r
344 setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
\r
349 // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
\r
350 $.fn.ajaxFormUnbind = function() {
\r
351 this.unbind('submit.form-plugin');
\r
352 return this.each(function() {
\r
353 $(":submit,input:image", this).unbind('click.form-plugin');
\r
359 * formToArray() gathers form element data into an array of objects that can
\r
360 * be passed to any of the following ajax functions: $.get, $.post, or load.
\r
361 * Each object in the array has both a 'name' and 'value' property. An example of
\r
362 * an array for a simple login form might be:
\r
364 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
\r
366 * It is this array that is passed to pre-submit callback functions provided to the
\r
367 * ajaxSubmit() and ajaxForm() methods.
\r
369 $.fn.formToArray = function(semantic) {
\r
371 if (this.length == 0) return a;
\r
373 var form = this[0];
\r
374 var els = semantic ? form.getElementsByTagName('*') : form.elements;
\r
375 if (!els) return a;
\r
376 for(var i=0, max=els.length; i < max; i++) {
\r
381 if (semantic && form.clk && el.type == "image") {
\r
382 // handle image inputs on the fly when semantic == true
\r
383 if(!el.disabled && form.clk == el)
\r
384 a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
\r
388 var v = $.fieldValue(el, true);
\r
389 if (v && v.constructor == Array) {
\r
390 for(var j=0, jmax=v.length; j < jmax; j++)
\r
391 a.push({name: n, value: v[j]});
\r
393 else if (v !== null && typeof v != 'undefined')
\r
394 a.push({name: n, value: v});
\r
397 if (!semantic && form.clk) {
\r
398 // input type=='image' are not found in elements array! handle them here
\r
399 var inputs = form.getElementsByTagName("input");
\r
400 for(var i=0, max=inputs.length; i < max; i++) {
\r
401 var input = inputs[i];
\r
402 var n = input.name;
\r
403 if(n && !input.disabled && input.type == "image" && form.clk == input)
\r
404 a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
\r
411 * Serializes form data into a 'submittable' string. This method will return a string
\r
412 * in the format: name1=value1&name2=value2
\r
414 $.fn.formSerialize = function(semantic) {
\r
415 //hand off to jQuery.param for proper encoding
\r
416 return $.param(this.formToArray(semantic));
\r
420 * Serializes all field elements in the jQuery object into a query string.
\r
421 * This method will return a string in the format: name1=value1&name2=value2
\r
423 $.fn.fieldSerialize = function(successful) {
\r
425 this.each(function() {
\r
428 var v = $.fieldValue(this, successful);
\r
429 if (v && v.constructor == Array) {
\r
430 for (var i=0,max=v.length; i < max; i++)
\r
431 a.push({name: n, value: v[i]});
\r
433 else if (v !== null && typeof v != 'undefined')
\r
434 a.push({name: this.name, value: v});
\r
436 //hand off to jQuery.param for proper encoding
\r
441 * Returns the value(s) of the element in the matched set. For example, consider the following form:
\r
444 * <input name="A" type="text" />
\r
445 * <input name="A" type="text" />
\r
446 * <input name="B" type="checkbox" value="B1" />
\r
447 * <input name="B" type="checkbox" value="B2"/>
\r
448 * <input name="C" type="radio" value="C1" />
\r
449 * <input name="C" type="radio" value="C2" />
\r
450 * </fieldset></form>
\r
452 * var v = $(':text').fieldValue();
\r
453 * // if no values are entered into the text inputs
\r
455 * // if values entered into the text inputs are 'foo' and 'bar'
\r
456 * v == ['foo','bar']
\r
458 * var v = $(':checkbox').fieldValue();
\r
459 * // if neither checkbox is checked
\r
461 * // if both checkboxes are checked
\r
462 * v == ['B1', 'B2']
\r
464 * var v = $(':radio').fieldValue();
\r
465 * // if neither radio is checked
\r
467 * // if first radio is checked
\r
470 * The successful argument controls whether or not the field element must be 'successful'
\r
471 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
\r
472 * The default value of the successful argument is true. If this value is false the value(s)
\r
473 * for each element is returned.
\r
475 * Note: This method *always* returns an array. If no valid value can be determined the
\r
476 * array will be empty, otherwise it will contain one or more values.
\r
478 $.fn.fieldValue = function(successful) {
\r
479 for (var val=[], i=0, max=this.length; i < max; i++) {
\r
481 var v = $.fieldValue(el, successful);
\r
482 if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
\r
484 v.constructor == Array ? $.merge(val, v) : val.push(v);
\r
490 * Returns the value of the field element.
\r
492 $.fieldValue = function(el, successful) {
\r
493 var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
\r
494 if (typeof successful == 'undefined') successful = true;
\r
496 if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
\r
497 (t == 'checkbox' || t == 'radio') && !el.checked ||
\r
498 (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
\r
499 tag == 'select' && el.selectedIndex == -1))
\r
502 if (tag == 'select') {
\r
503 var index = el.selectedIndex;
\r
504 if (index < 0) return null;
\r
505 var a = [], ops = el.options;
\r
506 var one = (t == 'select-one');
\r
507 var max = (one ? index+1 : ops.length);
\r
508 for(var i=(one ? index : 0); i < max; i++) {
\r
511 // extra pain for IE...
\r
512 var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
\r
523 * Clears the form data. Takes the following actions on the form's input fields:
\r
524 * - input text fields will have their 'value' property set to the empty string
\r
525 * - select elements will have their 'selectedIndex' property set to -1
\r
526 * - checkbox and radio inputs will have their 'checked' property set to false
\r
527 * - inputs of type submit, button, reset, and hidden will *not* be effected
\r
528 * - button elements will *not* be effected
\r
530 $.fn.clearForm = function() {
\r
531 return this.each(function() {
\r
532 $('input,select,textarea', this).clearFields();
\r
537 * Clears the selected form elements.
\r
539 $.fn.clearFields = $.fn.clearInputs = function() {
\r
540 return this.each(function() {
\r
541 var t = this.type, tag = this.tagName.toLowerCase();
\r
542 if (t == 'text' || t == 'password' || tag == 'textarea')
\r
544 else if (t == 'checkbox' || t == 'radio')
\r
545 this.checked = false;
\r
546 else if (tag == 'select')
\r
547 this.selectedIndex = -1;
\r
552 * Resets the form data. Causes all form elements to be reset to their original value.
\r
554 $.fn.resetForm = function() {
\r
555 return this.each(function() {
\r
556 // guard against an input with the name of 'reset'
\r
557 // note that IE reports the reset function as an 'object'
\r
558 if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
\r
564 * Enables or disables any matching elements.
\r
566 $.fn.enable = function(b) {
\r
567 if (b == undefined) b = true;
\r
568 return this.each(function() {
\r
569 this.disabled = !b
\r
574 * Checks/unchecks any matching checkboxes or radio buttons and
\r
575 * selects/deselects and matching option elements.
\r
577 $.fn.select = function(select) {
\r
578 if (select == undefined) select = true;
\r
579 return this.each(function() {
\r
581 if (t == 'checkbox' || t == 'radio')
\r
582 this.checked = select;
\r
583 else if (this.tagName.toLowerCase() == 'option') {
\r
584 var $sel = $(this).parent('select');
\r
585 if (select && $sel[0] && $sel[0].type == 'select-one') {
\r
586 // deselect all other options
\r
587 $sel.find('option').select(false);
\r
589 this.selected = select;
\r
594 // helper fn for console logging
\r
595 // set $.fn.ajaxSubmit.debug to true to enable debug logging
\r
597 if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
\r
598 window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
\r