Created
October 23, 2016 00:38
-
-
Save todofixthis/56189b6f12c17763beeb5820217057bb to your computer and use it in GitHub Desktop.
Serialize form inputs into JSON, with support for `name[]` syntax.
This file contains 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
(function($) { | |
$.extend($.fn, { | |
serializeJson: function() { | |
var payload = {}, | |
regex = /^(\w+)\[(\d*)\]$/; | |
$.each($(this).serializeArray(), function(i, input) { | |
var res = input.name.match(regex); | |
if(res) { | |
if(! (res[1] in payload)) { | |
payload[res[1]] = []; | |
} | |
var array = payload[res[1]]; | |
if(res[2] == '') { | |
array[array.length] = input.value; | |
} else { | |
// Ensure that the value gets inserted at exactly | |
// the right spot. | |
while(array.length < res[2]) { | |
array[array.length] = null; | |
} | |
array.splice(res[2], 0, input.value); | |
} | |
} else { | |
payload[input.name] = input.value; | |
} | |
}); | |
return JSON.stringify(payload); | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment