Last active
August 29, 2015 13:58
-
-
Save datchley/9967558 to your computer and use it in GitHub Desktop.
Dead simple function to serialize a form as a JSON object, using '.' notation in the field 'name' attribute and only serializing fields with a class of 'serialize'.
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
| window.serializeFormJSON = function(f) { | |
| var json = {}, | |
| $f = f.jquery ? f : $(f); | |
| $('input.serialize, select.serialize, textarea.serialize', $f).each(function(index, node) { | |
| var keypath = $(this).attr('name').split('.'), | |
| key = keypath.pop(), | |
| item = json; | |
| for (var i=0, l=keypath.length; i < l; i++) { | |
| if (!(keypath[i] in item)) { | |
| item[keypath[i]] = {}; | |
| } | |
| item = item[keypath[i]]; | |
| } | |
| item[key] = $(this).val() || null; | |
| }); | |
| return json; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment