Last active
September 30, 2019 10:40
-
-
Save rambabusaravanan/8eebfd7a9c828fd6121c8d8a48e08962 to your computer and use it in GitHub Desktop.
jQuery Serialize Object (JSON)
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
/** | |
* Usage: var json = $('#form-login').serializeObject(); | |
* Output: {username: "admin", password: "123456"} | |
* Output: {username: "admin", password: "123456", subscription: ["news","offer"]} | |
* */ | |
$.fn.serializeObject = function() { | |
var obj = {}; | |
var arr = this.serializeArray(); | |
arr.forEach(function(item, index) { | |
if (obj[item.name] === undefined) { // New | |
obj[item.name] = item.value || ''; | |
} else { // Existing | |
if (!obj[item.name].push) { | |
obj[item.name] = [obj[item.name]]; | |
} | |
obj[item.name].push(item.value || ''); | |
} | |
}); | |
return obj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment