jQuery: The Write Less, Do More JavaScript Library

Description

UPDATE: The Official Form Plugin now serializes forms much faster than this plugin.

This plugin will serialize a form into a hash of key/value pairs much faster than the form plugin's current serialize method, but it does so by ignoring the semantic order of the form elements. If semantic order isn't important to your application, this serializer will do the job at least 10 times faster (tested with a form containing over 2000 form elements).

Usage

To retrieve a hash of key/value pairs, just call the plugin on any jQuery form object:

var params = $('#myForm').fastSerialize();

This hash can be used in jQuery's AJAX methods, e.g.:

$.post('/path/to/script', $('#myForm').fastSerialize());

For a URL-ready string, pass the plugin's resultant hash to jQuery's param function:

var params = $('#myForm').fastSerialize();
var fragment = $.param( params );

Plugin Source

$.fn.fastSerialize = function() {
    var a = [];
    $('input,textarea,select,button', this).each(function() {
        var n = this.name;
        var t = this.type;
        if ( !n || this.disabled || t == 'reset' ||
            (t == 'checkbox' || t == 'radio') && !this.checked ||
            (t == 'submit' || t == 'image' || t == 'button') && this.form.clicked != this ||
            this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1)
            return;
        if (t == 'image' && this.form.clicked_x)
            return a.push(
                {name: n+'_x', value: this.form.clicked_x},
                {name: n+'_y', value: this.form.clicked_y}
            );
        if (t == 'select-multiple') {
            $('option:selected', this).each( function() {
                a.push({name: n, value: this.value});
            });
            return;
        }
        a.push({name: n, value: this.value});
    });
    return a;
};