Attribute id
of an element in HTML is used to define a single element in the DOM. That is, adding fields dynamically using an already defined id
makes no sense at all. The response of otaciojb has been concerned with this detail, but the solution is not the best, since by varying the name
attribute %, to retrieve 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 can see is to use []
in the element name, so in PHP we will get an array with all values entered. 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"])
would have ["1", "2", "3"]
.
In 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><divclass="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 Enviar
button and the result in the console were added to check the code operation, not being part of the original code, the implementation of the solution presented.
Remembering that if these dynamically added elements are already positioned within the form
element they will automatically be sent to PHP when the form is submitted.