1
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 the fields with the javascript
. I can also separate the values of inputs
day, beginning and end, for each of the forms.
But I would 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 $.ajax()
and with the PHP
insert into a collection
in the mongodb
.
How do I mount this object? I reinforce that my doubt is not as send via ajax and insert in mongodb. Just how 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.
The "day" key must be the field value
name="dia"
or simply the day, even string?– Phiter
In this case the value of the field.
– Diego de Lima