Last active
January 10, 2017 18:10
-
-
Save dux/f43dbf0cd8ffbe2d5a2a2ac56772cd59 to your computer and use it in GitHub Desktop.
JavaScript Zepto or jQuery plugin to serialize form data to hash
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
// 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; | |
}; |
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
/*** | |
$('#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