How to insert DIV with input fields inside the DIV using jquery or javascript

0

I have a simple form with add button that when I click it it adds 3 text inputs:

<form method="POST">
  <div id="ingredientes">
  </div>
  <button type="button" id="adicionar">Adicionar</button>
  <button type="submit">Cadastrar</button>
</form>

<script>
const adicionar = document.getElementById("adicionar");
const ingredientes = document.getElementById("ingredientes");
adicionar.addEventListener("click", function (event) {
  let div = document.createElement("div");
  let ing = document.createElement("input");
  ing.name = "ingredientes[]";
  ing.placeholder = "Ex: Cebola";
  ing.type="text";
  let qtd = document.createElement("input");
  qtd.name = "qtd[]";
  qtd.placeholder = "Ex: ¹/² colher de café";
  qtd.type="text";
  let pre = document.createElement("input");
  pre.name = "ingredientes[]";
  pre.placeholder = "Ex: Picada";
  pre.type="text";
  ingredientes.appendChild(ing);
  ingredientes.appendChild(qtd);
  ingredientes.appendChild(pre);
});
</script>

But now I would like that when adding, the 3 inputs would be inside the Div, it should insert like this:

<div id="ingredientes">
  <div>
    <input name="quantidade[]" placeholder="Ex: 1 colher de sopa" type="text">
    <input name="ingredientes[]" placeholder="Ex: Cebola" type="text">
    <input name="preparo[]" placeholder="Ex: Picada" type="text">
  </div>
</div>
    
asked by anonymous 10.09.2018 / 20:37

2 answers

2

const adicionar = document.getElementById("adicionar");
const ingredientes = document.querySelector("#ingredientes");
adicionar.addEventListener("click", function (event) {  
  let div = document.createElement("div");
  let ing = document.createElement("input");
  ing.name = "ingredientes[]";
  ing.placeholder = "Ex: Cebola";
  ing.type="text";
  let qtd = document.createElement("input");
  qtd.name = "qtd[]";
  qtd.placeholder = "Ex: ¹/² colher de café";
  qtd.type="text";
  let pre = document.createElement("input");
  pre.name = "ingredientes[]";
  pre.placeholder = "Ex: Picada";
  pre.type="text";  
  div.appendChild(ing);
  div.appendChild(qtd);
  div.appendChild(pre);
  ingredientes.appendChild(div);
});
<form method="POST">
  <div id="ingredientes">
   
  </div>
  <button type="button" id="adicionar">Adicionar</button>
  <button type="submit">Cadastrar</button>
</form>

Very simple, you only use document.createElement("div"); and add all the inputs inside the div created. After that, just give append , putting div created inside div #ingredientes .

I hope to have helped, good studies.

    
10.09.2018 / 20:44
-1

You can do this as follows:

$(div).append('<div>')

$(div).append(input)

$(div).append('</div>')
    
11.09.2018 / 05:55