Skip to content

Instantly share code, notes, and snippets.

@darrennolan
Created February 7, 2014 05:26
Show Gist options
  • Save darrennolan/8857727 to your computer and use it in GitHub Desktop.
Save darrennolan/8857727 to your computer and use it in GitHub Desktop.
jQuery Trim Serialize form function. Leaves previous form intact, allows for giving selector for trim to run on. Defaults to only input[type=text] inputs.
(function($) {
/**
* Trim Form Elements before returning Serialize()
* @param {string} selector Defaults to 'input[type=text]'
* @return {serialized()} Returned jQuery serialize() string
*/
$.fn.trimSerialize = function(selector) {
// Deep clone form (to get all nested elements), then unbind everything off the clone
var clonedObject = $(this).clone(true).off();
// Run over selector of each element, trim if matches found
selector = (selector === undefined) ? 'input[type=text]' : selector;
clonedObject.find(selector).each(function() {
$(this).val( $.trim( $(this).val() ) );
});
// Serialize the cloned object.
return clonedObject.serialize();
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment