Skip to content

Instantly share code, notes, and snippets.

@kovaldn
Created April 15, 2013 07:06
Show Gist options
  • Save kovaldn/5386281 to your computer and use it in GitHub Desktop.
Save kovaldn/5386281 to your computer and use it in GitHub Desktop.
Javascript: serialize functions
(function($) {
// Сериализовать форму в массив и убрать пустые элементы
$.fn.serializeArrayAndFilterEmpty = function() {
return $.grep(this.serializeArray(), function(item) {
return ($.trim(item.value).length > 0);
});
};
// сериализовать форму в массив (для моделей backbone)
$.fn.serializeObject = function(){
var obj = {}
$.each(this.serializeArrayAndFilterEmpty(), function(index, item){
obj[item.name] = item.value;
});
return obj;
};
// Сериализовать форму в json
$.fn.serializeToJSON = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment