jquery.serializeObject.min.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // Use internal $.serializeArray to get list of form elements which is consistent with $.serialize
  3. //
  4. // And to avoid names such as
  5. // => object["favorite-color"]
  6. //
  7. // We camelcase the name part, so the notation becomes
  8. // => object["favoriteColor"]
  9. //
  10. // Conveniently, this allows period notation to be used.
  11. // => object.favoriteColor
  12. //
  13. // This behaviour is similar to $(element).data()
  14. //
  15. // $('<div data-favorite-color="yellow"></div>').data()
  16. // => { favoriteColor: 'yellow' }
  17. //
  18. $.fn.serializeObject = function () {
  19. "use strict";
  20. var result = {};
  21. var mapper = function (element) {
  22. element.name = $.camelCase(element.name);
  23. return element;
  24. };
  25. var extend = function (i, element) {
  26. var node = result[element.name];
  27. // If node with same name exists already, need to convert it to an array as it
  28. // is a multi-value field (i.e., checkboxes)
  29. if ('undefined' !== typeof node && node !== null) {
  30. if ($.isArray(node)) {
  31. node.push(element.value);
  32. } else {
  33. result[element.name] = [node, element.value];
  34. }
  35. } else {
  36. result[element.name] = element.value;
  37. }
  38. };
  39. // For each serialzable element, convert element names to camelCasing and
  40. // extend each of them to a JSON object
  41. $.each($.map(this.serializeArray(), mapper), extend);
  42. return result;
  43. };