Skip to content

Instantly share code, notes, and snippets.

@robertuniqid
Created June 14, 2017 14:17
Show Gist options
  • Save robertuniqid/ac9023f3e965dfd08cb2553f5da09fe3 to your computer and use it in GitHub Desktop.
Save robertuniqid/ac9023f3e965dfd08cb2553f5da09fe3 to your computer and use it in GitHub Desktop.
jQuery Function to Serialize Object, like in a PHP $_POST request from HTML, the main issue came with combining checkboxes & hidden inputs, and I've made this adaptation to handle this..
$.fn.wpepSerializeObject = function () {
"use strict";
var result = {},
objectInstance = this;
var extend = function (i, element) {
var node = result[element.name];
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
// Lets make this ACT like a true PHP Request, seems like there's no famous post to include this.
jQuery.each( result, function( key, value ) {
if( ! ( value instanceof Array ) )
return;
if( key.endsWith("[]" ) )
return;
var checked_input = objectInstance.find( 'input[name="' + key + '"]:checked' );
if( checked_input.length > 0 ) {
result[key] = checked_input.val();
}
var hidden_input = objectInstance.find( 'input[name="' + key + '"][type="hidden"]' );
if( hidden_input.length > 0 ) {
result[key] = hidden_input.val();
}
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment