I have the following structure in html
:
<form id="titulo">
<input type="text" name="nome">
</form>
<form id="turno1">
<div class="linha">
<input type="text" name="dia">
<input type="text" name="inicio">
<input type="text" name="fim">
</div>
<div class="linha>
<input type="text" name="dia">
<input type="text" name="inicio">
<input type="text" name="fim">
</div>
</form>
<form id="turno2">
<div class="linha">
<input type="text" name="dia">
<input type="text" name="inicio">
<input type="text" name="fim">
</div>
<div class="linha>
<input type="text" name="dia">
<input type="text" name="inicio">
<input type="text" name="fim">
</div>
</form>
I can get the value of all fields with javascript
. I can also separate the values of the% day, beginning and end% for each of the forms.
However, I'd like to build a structure like this:
{
"nome" : [{
"turno1" : [{
"dia" : [{
"inicio" = "valor_inicio",
"fim" = "valor_fim"
}],
"dia" : [{
"inicio" = "valor_inicio",
"fim" = "valor_fim"
}],
}],
"turno2" : [{
"dia" : [{
"inicio" = "valor_inicio",
"fim" = "valor_fim"
}],
"dia" : [{
"inicio" = "valor_inicio",
"fim" = "valor_fim"
}],
}]
}
Then send via inputs
and with $.ajax()
insert in PHP
in collection
.
How do I mount this object? I reinforce that my question is not how to send via ajax and insert in mongodb. Only as I build this object.
After help, I was able to develop the following code:
var obj = {};
$("form").each(function (i) {
if (i == 0) {
form1 = $("[titulo='Nome']", $(this)).val();
obj[form1] = [{}];
} else {
formulario = $(this).attr("id");
linha = "#" + formulario + " .linha";
$(linha).each(function () {
obj[form1][0][formulario] = [{
[$("[name='dia']", $(this)).val()]: [{
"inicio": $("[name='inicio']", $(this)).val(),
"fim": $("[name='fim']", $(this)).val(),
}]
}]
});
}
});
But it returns only the value for the first line.