Guest User

Untitled

a guest
Jul 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1.  
  2. var CIDADES = {}
  3. CIDADES.Form = function(form_id) {
  4. if(!form_id) throw new Error("Formulário não informado");
  5. this.form = document.getElementById(form_id);
  6.  
  7. var _form = this.form;
  8.  
  9. var forEach = function(arr, fn) {
  10. for(var i = 0; i < arr.length; i++) {
  11. fn(arr[i]);
  12. }
  13. };
  14.  
  15. var getInput = function(id) {
  16. var input;
  17. var children = $("form#"+_form.id+" input");
  18. forEach(children, function(el) {
  19. if(el.id == id) input = el;
  20. });
  21. return input;
  22. };
  23.  
  24. var criarJson = function(id, valor) {
  25. var obj = id.split(".");
  26. var objeto = {};
  27. for(var t = obj.length; t > 0; t--) {
  28. var temp = {};
  29. var name = obj[t-1];
  30. if(name == obj[obj.length-1]) {
  31. temp[name] = valor;
  32. } else {
  33. temp[name] = objeto;
  34. }
  35. objeto = temp;
  36. }
  37. return objeto;
  38. };
  39.  
  40. var mesclar = (function mesclar(el, cp) {
  41. for(var i in cp) {
  42. if(typeof cp[i] == 'object') {
  43. if(typeof el[i] == "undefined") {
  44. el[i] = cp[i];
  45. }
  46. mesclar(el[i], cp[i]);
  47. } else {
  48. el[i] = cp[i];
  49. }
  50. }
  51. });
  52.  
  53. this.getValues = function() {
  54. var json = {};
  55. var children = $("form#"+_form.id+" input");
  56. forEach(children, function(input) {
  57. if(input.type == "text") {
  58. //json[input.id] = input.value
  59. var id = input.name;
  60. var valor = input.value
  61. var temp = criarJson(id, valor);
  62. mesclar(json, temp);
  63. }
  64. });
  65. return json;
  66. };
  67.  
  68. this.popular = function(json) {
  69.  
  70. (function percorrer(el, pai){
  71. for(var propriedade in el) {
  72. var value = el[propriedade];
  73. if( typeof value == "object" ) {
  74. if(typeof pai == "undefined") {
  75. var pai = propriedade;
  76. } else {
  77. pai = pai + "." + propriedade;
  78. }
  79. percorrer(value, pai);
  80. } else {
  81. var input;
  82. if(typeof pai == "undefined") {
  83. input = getInput(propriedade);
  84. } else {
  85. input = getInput(pai + "." + propriedade);
  86. }
  87. if(input) input.value = value;
  88. }
  89.  
  90. }
  91.  
  92. })(json)
  93.  
  94. return this;
  95. };
  96.  
  97. return this;
  98. };
Add Comment
Please, Sign In to add comment