Skip to content

Instantly share code, notes, and snippets.

@ykessler
Created February 25, 2021 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykessler/5f0f0b1b144c60578b59de859a0e4251 to your computer and use it in GitHub Desktop.
Save ykessler/5f0f0b1b144c60578b59de859a0e4251 to your computer and use it in GitHub Desktop.
.serializeToObject() - A jQuery plugin for serializing form data to object
// TAKEN FROM: https://stackoverflow.com/a/8407771/165673
// IMPORTANT: This does NOT work with nested 'something[other]' type names.
//
// NOTES:
// - To avoid serializing certain input controls, tag them with '.no_serialize' class.
// - Will also ignore any inputs that don't have a name assigned.
// - Handles jQuery UI datepickers well. Doesn't care what format the datepicker uses.
// It will use whatever date format use pass as an option to .serialize_to_object().
//
// REQUIRES:
// - moment.js
//
(function($){
$.fn.serializeToObject = function(options){
var default_options = {
date_format: 'YYYY-MM-DD', // The date format into which jQuery UI datepicker values will be serialized.
include_disabled: false // Serialize disabled form elements.
}
options = _.extend(default_options, options);
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
// Identify all jQuery UI datepickers:
var datepickers = [];
$.each($(this).find('.hasDatepicker'), function(){
datepickers.push($(this).attr('name'));
});
// Select all serializable form controls:
var $serializable_form_controls = $(this).find('*:not(".no_serialize")');
// Temporarily enable disabled form items if we want them serialized.
// SEE: https://stackoverflow.com/a/45741385/165673
if (options.include_disabled){
var disabled = this.find(":input:disabled").removeAttr("disabled");
}
$.each($serializable_form_controls.serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
// Reformat all datepicker values:
if (datepickers.indexOf(this.name) != -1) {
// Use moment.js to convert to another format without timezone/UTC fuckery:
// (SEE https://stackoverflow.com/a/38917006/165673)
var reformatted_date_string = moment(this.value).format(options.date_format);
this.value = reformatted_date_string;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
// Re-disable items:
if (options.include_disabled){
disabled.attr("disabled", "disabled");
}
// ADDED LOGIC:
// Get rid of empty (null or blank) values
// FROM: https://stackoverflow.com/a/23774287/165673
$.each(json, function(key, value){
if (value === "" || value === null){
delete json[key];
}
});
return json;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment