The solution with textarea
is bad and not usual. The function of this element is to store a text, not a list, so using it is wrong and not semantic. If your problem is having 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 ingredient field as ingredientes[]
, square brackets at the end. PHP, when parsing this data, will convert to a 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 make more elements be created by pressing the button Add. 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>
This way, when pressing the button Add, another ingredient field is added. This even 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 get the list of ingredients with:
$ingredientes = $_POST["ingredientes"];
Will be a array with all the ingredients typed.
Can it be using javascript? Or would it just be php?
– David Alves
can yes, jquery, whatever you need...
– Leandro Marzullo