Attribute id
of an element in HTML serves to define an element single in DOM. That is, add fields dynamically using a id
already defined does not make any sense. A reply otaciojb was concerned with this detail, but the solution is not the best, because varying the attribute name
, to recover the values in PHP it would be necessary to know how many fields there are and check each global variable $_POST["episodioX"]
, where X is a variable value.
The best way I see is to use []
in the element name, this way, in PHP, we will receive a array with all values reported. For example:
<input type="text" name="episodios[]" value="1">
<input type="text" name="episodios[]" value="2">
<input type="text" name="episodios[]" value="3">
In PHP, doing var_dump($_POST["episodios"])
we would have ["1", "2", "3"]
.
This way, your code would look something like:
var episodios = 1;
$("#addEpisodeField").on("click", function(event) {
episodios++;
$("#episodeField").append("<input name=\"episodios[]\" type=\"text\" value=\"Episódio " + episodios + "\" class=\"form-control input-md\">");
});
$("button").on("click", function (event) {
console.log($("form").serializeArray());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Episódios</label>
<div class="col-md-3" name="episodeField" id="episodeField">
<input id="textinput" name="episodios[]" type="text" value="Episódio 1" class="form-control input-md">
</div>
<a href="#" id="addEpisodeField" class="addEpisodeField">+</a>
<button type="button">Enviar</button>
</div>
</form>
Note: The button Enviar
and the result in console were added to verify the functioning of the code, not being part of the original code, nor being essential for the implementation of the presented solution.
Remembering that if these added elements dynamically are already positioned inside the element form
will automatically be sent to PHP when the form is submitted.
The solution worked for me, I had to make some changes but it worked. Thank you very much!
– Otavio Rocha