The solution with textarea
is bad and unusual. The function of this element is to store a text, not a list, so using it is wrong and nothing semantic. If your problem is to have multiple ingredient fields, your HTML should be consistent with this idea: have multiple fields.
Since you are using PHP on the server, you can set the name of the ingredients field to ingredientes[]
, with the brackets at the end. PHP, when parsing this data, will convert to an array . So your HTML would look something like:
input {
display: block;
margin-bottom: 10px;
}
<form method="POST">
<label for="receita">Receita:</label>
<input type="text" name="receita" placeholder="Ex: Pão de queijo">
<label>Ingredientes:</label>
<div id="ingredientes">
<input type="text" name="ingredientes[]" placeholder="Ex: Sal">
</div>
<button type="button" id="adicionar">Adicionar</button>
<button type="submit">Cadastrar</button>
</form>
So to add more ingredients, just have more elements created by pressing the Add button. With JavaScript, we can do something like:
const adicionar = document.getElementById("adicionar");
const ingredientes = document.getElementById("ingredientes");
adicionar.addEventListener("click", function (event) {
let campo = document.createElement("input");
campo.name = "ingredientes[]";
campo.placeholder = "Ex: Sal";
ingredientes.appendChild(campo);
});
input {
display: block;
margin-bottom: 10px;
}
<form method="POST">
<label for="receita">Receita:</label>
<input type="text" name="receita" placeholder="Ex: Pão de queijo">
<label>Ingredientes:</label>
<div id="ingredientes">
<input type="text" name="ingredientes[]" placeholder="Ex: Sal">
</div>
<button type="button" id="adicionar">Adicionar</button>
<button type="submit">Cadastrar</button>
</form>
In this way, when the Add button is pressed, another field for ingredient is added. This also allows the user to edit the information of any ingredient and, if implemented, remove ingredients as well.
On the server side, when the form is submitted, you can pick up the ingredient list with:
$ingredientes = $_POST["ingredientes"];
It will be an array with all the ingredients typed in.