Correctifs
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage_django / media / js / form.js
CommitLineData
5ecd5424
CR
1var JSONForm = function (schemadiv, formdiv, sourcediv) {
2 this._schema = JSON.parse ($("#"+schemadiv).html());
3 this._form = $("#"+formdiv);
4 this._source = $("#"+sourcediv);
5
6 this.addToList = JSONForm.addToList;
7 this.setup = JSONForm.setup;
8
9 this.readList = JSONForm.readList;
10 this.serialize = JSONForm.serialize;
11}
12
13JSONForm.addToList = function (divid, no) {
14 $("<p><input type='text' id='" + divid + no + "' /></p>").appendTo ("#"+divid);
15}
16
17JSONForm.setup = function () {
18 // Initial stuff
19 var initial = {};
20 if (this._source.html().length > 0) {
21 initial = JSON.parse (this._source.html());
22 }
23
24 var form = "<table>";
25 for (k in this._schema.mapping) {
26 var field = this._schema.mapping[k];
27 if (field.hidden != true) {
28 form += "<tr><td>";
29 if (typeof(field.title) != 'undefined')
30 form += field.title;
31 else
32 form += k;
33 form += "</td><td>";
34
35 var value = initial[k];
36 if (typeof (value) == 'undefined')
37 value = "";
38
39 var id = "field_" + k;
40
41 if (field.type == "text") {
42 form += "<textarea id='"+id+"'>"+value+"</textarea>"
43 }
44 else if (field.type == "str") {
45 form += "<input id='"+id+"' type=\"text\" value=\""+value+"\" />"
46 }
47 else if (field.type == "seq") {
48 form += "<div id='"+id+"'>";
49 var i = -1;
50 for (i in value) {
51 form += "<p><input type='text' id='" + id + i
52 + "' value=\"" + value[i].replace(/"/g, "\\\"") + "\" /></p>";
53 }
54 form += "</div><p align=\"left\">[<a href=\"#\" id='add_" + id
55 + "' onclick='JSONForm.addToList(\"" + id + "\", "
56 + (parseInt(i) + 1) + ");'>+</a>]</p>";
57 }
58 form += "</td></tr>";
59 }
60 }
61 form += "</table>";
62 this._form.html (form);
63}
64
65JSONForm.readList = function (list) {
66 var rc = [];
67 var nodes = list.find("input[type='text']").toArray();
68 for (var i in nodes)
69 if (nodes[i].value.length > 0)
70 rc.push (nodes[i].value);
71 return rc;
72}
73
74JSONForm.serialize = function () {
75 var root = {};
76 if (this._source.html().length > 0) {
77 root = JSON.parse (this._source.html());
78 }
79 for (k in this._schema.mapping) {
80 var field = this._schema.mapping[k];
81 if (field.hidden != true) {
82 var value = "";
83 if (field.type == 'str' || field.type == 'text')
84 value = $("#field_"+k).val().trim ();
85 else if (field.type == 'seq')
86 value = this.readList ($("#field_"+k));
87
5ecd5424
CR
88 if (value.length > 0)
89 root[k] = value;
90 else
91 delete (root[k]);
92 }
93 }
94 //alert (JSON.stringify(root));
95 this._source.html (JSON.stringify(root));
96}
97