I need to create a web page dynamic, where a layman User can enter information as if he were editing an XML or JSON, and after that need to convert this html in a json.
To convert html json already I found several examples using ajax for example, like this:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
You could try:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test 1</title>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
createTextBox('formulario','campo1','valor1');
});
function createTextBox(parent, name, value)
{
var node = '<div class="node" id="node_'+name+'">'
+ '<input placeholder="" type="text" id="value_'+name+'" name="value_'+name+'" value="'+value+'" />'
+ '<input placeholder="" type="text" id="value2_'+name+'" name="value2_'+name+'" value="'+value+'" />'
+ '<input placeholder="" type="text" id="parent_'+name+'" name="parent_'+name+'" value="'+parent+'" />'
+ '<div id="nested_'+name+'" style="padding-left: 10%;" ><a href="#" onclick="addNested(this)" >ADD NESTED</a></div>'
+'</div>';
$('#'+parent).append(node);
//parse2Json();
}
function addNested(object)
{
var name = getNewName();
createTextBox(object.parentElement.id, name , name);
}
function getRandomName() {
var ret;
if (!Date.now) {
ret = function() { return new Date().getTime();
}
} else {
ret = Date.now();
}
return ret;
}
function getNewName() {
var ret = $("#count_campo").val();
$("#count_campo").val(parseInt(ret)+1);
return ret;
}
function parse2Json()
{
//pegando todos os elementos node
$('.node').each(function(index, obj) {
alert("pai:"+ obj.parentElement.id);
alert("id:"+ obj.id);
alert("Campo 1: Id["+$("#"+obj.id).children(1).attr('name') +"] Value["+$("#"+obj.id).children(1).val()+"]");
alert("Campo 2: Id["+$("#"+obj.id).children(2).attr('name') +"] Value["+$("#"+obj.id).children(2).val()+"]"); // IGUAL -> //var c = obj.childNodes[2].text;
//getting all elements inside div
var array = Array.prototype.slice.call(obj.childNodes);
array.forEach(function(objecto_filho) {
alert("Dentro Foreach: "+ objecto_filho.id);
});
//ou
});
}
</script>
</head>
<body>
<input type="text" id="count_campo" name="count_campo" value="1" />
<h1>Testes XML config</h1>
<div id="formulario">
</div>
</body>
</html>