Created
April 15, 2013 07:06
-
-
Save kovaldn/5386281 to your computer and use it in GitHub Desktop.
Javascript: serialize functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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