Delete dynamic input

Asked

Viewed 88 times

1

I am using javascript to create inputs dynamically. I create a phone and email input this way.

I created a deleteEmail() function that deletes the latest created one, however when I create other fields I lose the reference from which to delete

What I want to know is how I delete these inputs created using pure JS?

 function addEmail(){
    var container = document.getElementById("box");
    var input = document.createElement("input");
    var label = document.createElement("label");
    var btn_delete = document.createElement("button");
    var br = document.createElement("br");

    input.type = "text";
    input.name = "email";

    label.innerText = "Email";
    label.htmlFor = "email";

    btn_delete.type = "button"
    btn_delete.innerText = "Deletar";
    btn_delete.id = "btn-delete";


    container.appendChild(br);

    container.appendChild(btn_delete);
    container.appendChild(input);   
    container.appendChild(label);


    document.getElementById("btn-delete").onclick = function () {deleteEmail()};

    function deleteEmail(){
        btn_delete.remove();
        input.remove();
        br.remove();
        label.remove();
    }

}

Here’s the fiddle with the whole code https://jsfiddle.net/5munzeja/

2 answers

1

You actually have several problems with your code, the first being the creation of repeated id’s. Note that you assign a id same as each button:

btn_delete.id = "btn-delete";

That will make you have multiple buttons on the page with equal id’s, which is wrong and in some case will make your page not do some things properly.

In addition said you assign the new elements in the local variables input, label, btn_delete and br maids with var, soon can only reach the last created.

The simplest solution that makes html correct is to assign classes instead of ids, and change the declaration of variables that store the new elements to let:

function addEmail() {
  var container = document.getElementById("box");
  
  let input = document.createElement("input");  //com let
  let label = document.createElement("label");  //com let
  let btn_delete = document.createElement("button"); //com let
  let br = document.createElement("br"); //com let

  input.type = "text";
  input.name = "email";

  label.innerText = "Email";
  label.htmlFor = "email";

  btn_delete.type = "button"
  btn_delete.innerText = "Deletar";
  btn_delete.classList.add("btn-delete"); //adicionar a classe com classList
  
  container.appendChild(br);

  container.appendChild(btn_delete);
  container.appendChild(input);
  container.appendChild(label);

  btn_delete.onclick = function() { //handler de click aplicado diretamente
     input.remove();
     label.remove();
     btn_delete.remove();
     br.remove();
  };
}
<div id="box">
</div>
<button type="button" id="criar-input" onclick="addEmail()">Criar Novo Email</button>

I just changed the lines of code that have comments. Changing the class with the classList makes your html correct, but what makes the remove work is the let. This is due to closures which are not applied equally to var and let. You should read the link to closures to deepen further on this subject.

I kept the class assignment to be consistent with the logic I had, but the way the code is it’s not necessary to remove it working, and it’s something you can take out if you want.

Of course, there are other alternatives that do not make use of that detail, but involve exchanging much more in their example and some are more elaborate. A simple alternative is to make use of html navigation, and for your example could include all elements in a new div, and delete that div by browsing the DOM with closest or parentElement.

1

Good night, Rodrigo, all right? What you can do is store these references in the DOM itself, whether they are by id, classes or etc. This will depend a lot on how you work, and the behavior you want. I made a little reproduction of something you can take as a basis.

function deletarForm(id){
 	const el = document.getElementById(id);
  el.remove()
 }
document.getElementById('btn').addEventListener('click', ()=> {
	const container = document.getElementById('container');
	const newContactField = document.createElement('div');
  const deleteButton = document.createElement('button');
  deleteButton.innerHTML = 'excluir';
  deleteButton.addEventListener('click', () => deletarForm(id));

  const id = `contato-${container.childElementCount}`;
  newContactField.id = id;
  newContactField.innerHTML = `
  <input type="text" placeholder="digite aqui">
    `
  newContactField.appendChild(deleteButton);
container.appendChild(newContactField);
  
});
<div id="container">
  
</div>
<button id='btn'>Adicionar novo contato</button>

This is one of the strategies, it is something very basic but it will serve you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.