Reputation: 2274
I have a form to register an unlimited number of telephone nums in which I dynamically add some more input fields as the users needs it, so it is defined as (using Laravel html helpers):
<h3>Telefone(s):</h3> <a id="add-tel" class="btn btn-danger" data-qtdtels="1">+</a>
<div class="row">
<div id="cad-telefone" class="col-md-12 text-center">
<div class="row">
<div class="col-md-4">
<label for="ddi1">Código internacional (DDI):</label>
{{ Form::number('ddi1', 55, array('class' => 'form-control', 'placeholder' => 'DDI' )) }}
</div>
<div class="col-md-4">
<label for="ddd1">Código regional (DDD):</label>
{{ Form::number('ddd1', null, array('class' => 'form-control', 'placeholder' => 'DDD' )) }}
</div>
<div class="col-md-4">
<label for="numero1">Número do telefone</label>
{{ Form::text('numero1', null, array('class' => 'form-control', 'maxlength' => '20', 'placeholder' => 'Nro Telefone' )) }}
</div>
</div>
</div>
Whenever the button with id add-tel
is pressed, it runs the script which adds the extra input fields, notice the name
of the input field is defined according to the number of inputs:
$("#add-tel").on("click", function(){
// qtdtels = the number of input fields
var qtdtels = parseInt($(this).attr("data-qtdtels"));
qtdtels += 1;
$(this).attr("data-qtdtels", qtdtels);
qtdtels = qtdtels.toString();
var text = "<br><div class=\"row\">";
text += "<div class=\"col-md-4\">";
text += "<input class=\"form-control\" placeholder=\"DDI\" name=\"ddi" + qtdtels + "\" value=\"55\" type=\"number\">";
text += "</div>";
text += "<div class=\"col-md-4\">";
text += "<input class=\"form-control\" placeholder=\"DDD\" name=\"ddd" + qtdtels + "\" type=\"number\">";
text += "</div>";
text += "<div class=\"col-md-4\">";
text += "<input class=\"form-control\" maxlength=\"20\" placeholder=\"Nro telefone\" name=\"numero" + qtdtels + "\" type=\"text\">";
text += "</div>";
text += "</div>";
$(text).appendTo("#cad-telefone");
});
The process runs normally on client side and the new inputs are given. The problem is, when I submit the code, on the $request
it is only posted the fields ddi1
,ddd1
,numero1
. All other dynamically added fields like ddiX
,dddX
,numeroX
are not present. How to make it so I can add more input fields to the POST
?
Upvotes: 1
Views: 1003
Reputation: 1
The HTML created within #add-tel
click
handler is not appended to an existing <form>
element within document
. The generated HTML is appended to div#cad-telefone
. When an existing <form>
is submitted the dynamically created HTML including <input>
elements are not child nodes of the the existing <form>
elements at HTML.
You can append the HTML to an existing <form>
element in document
, or create and append a new <form>
for each collection of HTML <input>
elements then append the generated HTML to the new <form>
element.
Upvotes: 1