Skip to content

Instantly share code, notes, and snippets.

@dux
Last active January 10, 2017 18:10
Show Gist options
  • Save dux/f43dbf0cd8ffbe2d5a2a2ac56772cd59 to your computer and use it in GitHub Desktop.
Save dux/f43dbf0cd8ffbe2d5a2a2ac56772cd59 to your computer and use it in GitHub Desktop.
JavaScript Zepto or jQuery plugin to serialize form data to hash
// using built in jQuery and Zepto serializeArray()
/***
$('#form').serializeHash()
should return :
{
'user[name]': 'Dux'
}
***/
$.fn.serializeHash = 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 || '';
}
});
console.log(o);
return o;
};
/***
$('#form').serializeHash()
should return :
{
user: {
'name': 'Dux'
}
}
***/
$.fn.serializeHash = function() {
var hash = {};
function stringKey(key, value) {
var beginBracket = key.lastIndexOf('[');
if (beginBracket == -1) {
var hash = {};
hash[key] = value;
return hash;
}
var newKey = key.substr(0, beginBracket);
var newValue = {};
newValue[key.substring(beginBracket + 1, key.length - 1)] = value;
return stringKey(newKey, newValue);
}
$(this).find('input, textarea, select').each(function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /hidden|text|search|tel|url|email|password|datetime|date|month|week|time|datetime-local|number|range|color/i.test(this.type))) {
var val = $(this).val();
$.extend(true, hash, stringKey(this.name, val));
}
});
return hash;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment