Javascript error while trying to remove element

Asked

Viewed 78 times

0

I made a method to remove an item from my table HTML which is supplied by a standard form but the information goes to the table in question... Until then everything normal, but when removing a new item, other than what was previously registered, does not remove.

Here’s my project with the bug, hosted for you to take a look at what I’m talking about: https://wesleyvicen1535.000webhostapp.com/CadastroPaciente.html

So far so quiet, the script quietly removes items with the class "remove", but the new implemented items do not. They can inspect element that will show that the new ones are going with the class.

My repository on Github with the source code: https://github.com/wesleyvicen/ProjetoWebOdontologia

Remove method:

var removerTds = document.querySelectorAll('.remover');

removerTds.forEach(function (item) {
    item.addEventListener('dblclick', function () {
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            item.parentNode.remove();
        }
    })
});

Implements the table:

var botao_cadastrar = document.querySelector("#btn_cadastrar");

 botao_atendimento.addEventListener("click", function () {
        event.preventDefault();
        adicionar_atendimento();

    });

function adicionar_cadastro() {
    var nome = document.querySelector('#nome').value;
    var sobrenome = document.querySelector('#sobrenome').value;
    var cpf = document.querySelector('#cpf').value;
    var endereco = document.querySelector('#endereco').value;
    var numero = document.querySelector('#numero').value;
    var bairro = document.querySelector('#bairro').value;
    var cep = document.querySelector('#cep').value;
    var cep2 = document.querySelector('#cep2').value;
    var uf = document.querySelector('#uf').value;
    var cidade = document.querySelector('#cidade').value;
    var municipio = document.querySelector('#municipio').value;

    var tabela = document.querySelector(".tabelaCadastroCliente");

    var linha = document.createElement('tr');
    var td_nome = document.createElement('td');
    var td_sobrenome = document.createElement('td');
    var td_cpf = document.createElement('td');
    var td_endereco = document.createElement('td');
    var td_numero = document.createElement('td');
    var td_bairro = document.createElement('td');
    var td_cep = document.createElement('td');
    var td_uf = document.createElement('td');
    var td_cidade = document.createElement('td');
    var td_municipio = document.createElement('td');
    var td_remover = document.createElement('td');


    td_nome.textContent = nome +' '+ sobrenome;
    td_cpf.textContent = cpf;
    td_endereco.textContent = endereco;
    td_numero.textContent = numero;
    td_bairro.textContent = bairro;
    td_cep.textContent = cep +'-'+ cep2;
    td_uf.textContent = uf;
    td_cidade.textContent = cidade;
    td_municipio.textContent = municipio;
    td_remover.textContent = 'Remover';
    td_remover.classList.add('remover')

    linha.appendChild(td_nome);
    linha.appendChild(td_cpf);
    linha.appendChild(td_endereco);
    linha.appendChild(td_numero);
    linha.appendChild(td_bairro);
    linha.appendChild(td_cep);
    linha.appendChild(td_uf);
    linha.appendChild(td_cidade);
    linha.appendChild(td_municipio);
    linha.appendChild(td_remover);

    tabela.appendChild(linha);
};
  • Wesley, this happens because the element was not rendered when the page was loaded, on the contrary, you created the same after the whole process, to solve, you must define the event within the function adicionar_cadastro see: td_remover.addEventListener('dblclick' ...

  • I understood what you said, but I don’t understand how I can solve @Noobsaibot

  • Thank you very much, solved my problem, but is there any way to call again the method without being repeating code?

  • Yes, you can create a function and pass it: td_remover.addEventListener('dblclick', funcaoParaRemover); , just have to change td_remover.parentNode.remove(); for this.parentNode.remove();

  • Wesley welcome, as a new user, it is important to know how the site works, I recommend you read the [tour] and if you need help on how to use the tool, go to [help].

  • See here the example of as I said earlier.

  • Thank you very much, you helped me a lot

Show 2 more comments

2 answers

0

/**
*
* Use assim que funciona
*
*/
var removerTds = document.querySelectorAll('.remover');

for(i = 0; i < removerTds.length; i++)
{
	removerTds[i].addEventListener('click', function(){
		var confirmacao = confirm('Deseja realmente remover este item?')
		if(confirmacao){
			this.parentNode.remove();
		}
	});
}

0

Add the event dblclick to the object document and check if the clicked element has the class .remover. This way will detect double clicking also on the new buttons added dynamically, and you will not need to do forEach to add the event to each button.

Remembering that the function .remove() does not work in Internet Explorer. If that’s an inconvenience, change it to .outerHTML = '';.

See below for what has been removed and what has been added to your original code:

// CÓDIGO REMOVIDO

//var removerTds = document.querySelectorAll('.remover');

//removerTds.forEach(function (item) {
//    item.addEventListener('dblclick', function () {
//        var confirmacao = confirm('Deseja realmente remover este item?')
//        if (confirmacao) {
//            item.parentNode.remove();
//        }
//    })
//});

// CÓDIGO ADICIONADO
document.addEventListener('dblclick', function(e){

   if(e.target.className == 'remover'){
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            e.target.parentNode.remove();
        }
   }

});

The e.target is the clicked element that triggered the event, the .className returns the class of the element.

Functioning:

// CÓDIGO REMOVIDO

//var removerTds = document.querySelectorAll('.remover');

//removerTds.forEach(function (item) {
//    item.addEventListener('dblclick', function () {
//        var confirmacao = confirm('Deseja realmente remover este item?')
//        if (confirmacao) {
//            item.parentNode.remove();
//        }
//    })
//});

// CÓDIGO ADICIONADO
document.addEventListener('dblclick', function(e){
   
   if(e.target.className == 'remover'){
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            e.target.parentNode.remove();
        }
   }
   
});
// FIM CÓDIGO ADICIONADO


var botao_atendimento = document.querySelector("#btn_atendimento");
var botao_cadastrar = document.querySelector("#btn_cadastrar");

//O IF agora vai selecionar qual dos botões foi clicado, se foi o do atendimento ou do cadastro.
if (botao_atendimento) { // criei este If e o proximo para não ficar sempre puxando o preventDefault()
    botao_atendimento.addEventListener("click", function () {
        event.preventDefault(); // Pega o evento e interrompe o evento normal
        adicionar_atendimento();

    });
} else if (botao_cadastrar) {
    botao_cadastrar.addEventListener("click", function () {
        event.preventDefault();
        adicionar_cadastro();

    });
}

//Metodo usado para o atendimento
function adicionar_atendimento() {
    var nome = document.querySelector('#nome').value; // Seleciona um elemento, neste caso o ID Nome
    var data = document.querySelector('#data').value;
    var descricao = document.querySelector('#descricao').value;

    var tabela = document.querySelector(".tabelaAtendimento");

    var linha = document.createElement('tr'); // Cria um elemento, neste Caso um tr
    var td_nome = document.createElement('td');
    var td_data = document.createElement('td');
    var td_descricao = document.createElement('td');

    td_nome.textContent = nome; // Retorna um nó do createElement, neste caso do td_nome
    td_data.textContent = data;
    td_descricao.textContent = descricao;

    linha.appendChild(td_nome); // Devolve uma referência ao nó adicionado, neste caso o td_nome
    linha.appendChild(td_data);
    linha.appendChild(td_descricao);

    tabela.appendChild(linha); // aqui retorna a referência ao nó adicionado no linha
};

function adicionar_cadastro() {
    var nome = document.querySelector('#nome').value;
    var sobrenome = document.querySelector('#sobrenome').value;
    var cpf = document.querySelector('#cpf').value;
    var endereco = document.querySelector('#endereco').value;
    var numero = document.querySelector('#numero').value;
    var bairro = document.querySelector('#bairro').value;
    var cep = document.querySelector('#cep').value;
    var cep2 = document.querySelector('#cep2').value;
    var uf = document.querySelector('#uf').value;
    var cidade = document.querySelector('#cidade').value;
    var municipio = document.querySelector('#municipio').value;

    var tabela = document.querySelector(".tabelaCadastroCliente");

    var linha = document.createElement('tr');
    var td_nome = document.createElement('td');
    var td_sobrenome = document.createElement('td');
    var td_cpf = document.createElement('td');
    var td_endereco = document.createElement('td');
    var td_numero = document.createElement('td');
    var td_bairro = document.createElement('td');
    var td_cep = document.createElement('td');
    var td_uf = document.createElement('td');
    var td_cidade = document.createElement('td');
    var td_municipio = document.createElement('td');
    var td_remover = document.createElement('td');


    td_nome.textContent = nome +' '+ sobrenome;
    td_cpf.textContent = cpf;
    td_endereco.textContent = endereco;
    td_numero.textContent = numero;
    td_bairro.textContent = bairro;
    td_cep.textContent = cep +'-'+ cep2;
    td_uf.textContent = uf;
    td_cidade.textContent = cidade;
    td_municipio.textContent = municipio;
    td_remover.textContent = 'Remover';
    td_remover.classList.add('remover')

    linha.appendChild(td_nome);
    linha.appendChild(td_cpf);
    linha.appendChild(td_endereco);
    linha.appendChild(td_numero);
    linha.appendChild(td_bairro);
    linha.appendChild(td_cep);
    linha.appendChild(td_uf);
    linha.appendChild(td_cidade);
    linha.appendChild(td_municipio);
    linha.appendChild(td_remover);

    tabela.appendChild(linha);
};
/* RESET */

body {
    margin: 20px 0 0 0;
    padding: 0;
    font-family: Tahoma;
    box-sizing: border-box;
    border: none;
    outline: none;
    background-color: #f5f5f5
}

.corpo {
    width: 100%;
    height: 180px;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);

}

.tabela {
    border: 2px solid white;
    position: absolute;
    text-align: center;
    width: 100%;
}

.centro {
    text-align: center;
    width: 100%;
}

article {
    display: inline-grid;
    margin-bottom: 20px;
}

article:hover {
    border: 5px inset;
}

article span {
    color: ce2e3c;
    font-weight: 550;
}

/* Campos de formulário genéricos */


table {
    border-collapse: collapse;
    padding-right: 20px;
}

th,
td {
    padding: 10px;
}

tr:nth-child(odd) {
    background-color: #f7f7f7;
    border-bottom: 1px solid #444
}

tr:nth-child(even) {
    background-color: #f1f1f1;
    border-bottom: 1px solid #444
}

td:hover {
    background-color: #dedede;
}

tfoot td {
    background-color: #444;
    color: #fff;
    text-align: center;
    font-weight: bolder;
}

tfoot td:hover {
    background-color: #444;
}

textarea {
    width: 500px;
    height: 200px;
    padding: 20px;
}

#cep {
    width: 6%;
}

#cep2 {
    width: 5%;
}

.btn {
    border-radius: 12px;
    width: 330px;
    height: 45px;
    margin: 0.5em;
    background-color: #f48888;
    color: white;
    font-weight: 600;
}

#acao {
    background-color: red;
    color: white;
}

.remover {
    background-color: darkred;
    color: white;
    cursor: hand;
}

.remover:hover {
    background-color: red;

}

.btn:hover {
    background-color: #f26464
}

textarea,
input[type="text"],
input[type="datetime-local"],
input[type="search"],
input[type="number"] {
    border: 2px #cccccc solid;
    border-radius: 10px;
    padding: 0 20px;
}


input[type="text"],
input[type="datetime-local"],
button[type="submit"],
input[type="search"],
input[type="number"] {
    height: 32px;
    font-family: Tahoma;
    font-size: 14px;
}

textarea:hover,
input[type="text"]:hover,
input[type="datetime-local"]:hover,
input[type="search"]:hover,
input[type="number"]:hover {
    background-color: #ddddff;
}

textarea:focus,
input[type="text"]:focus,
input[type="datetime-local"]:focus,
input[type="search"]:focus,
input[type="number"]:focus {
    background: #ffcccc;
}
    <main class="centro">
        <form class="form">
            <input id="nome" type="text" placeholder="Nome" name="nome" autofocus>
            <input id="sobrenome" type="text" placeholder="Sobrenome" name="sobrenome"><br>
            <input id="cpf" type="number" placeholder="CPF" name="cpf" maxlength="11"><br>
            <input id="endereco" type="text" placeholder="Endereço" name="endereco">
            <input id="numero" type="number" placeholder="Número" name="numero"><br>
            <input id="bairro" type="text" placeholder="Bairro" name="bairro"><br>
            <input id="cep" type="text" name="cep" size="3" maxlength="5" placeholder="CEP"> - <input id="cep2" placeholder="CEP" type="text" name="cep2" size="3" maxlength="3"><br>
            <input id="uf" type="text" placeholder="UF" name="uf" maxlength="2"><br>
            <input id="cidade" type="text" placeholder="Cidade" name="cidade"><br>
            <input id="municipio" type="text" placeholder="Distrito" name="municipio"><br>
            <button id="btn_cadastrar" class="btn" type="submit" style="cursor:hand" name="cadastrar">Cadastrar</button>
        </form>

        <table class="tabela tabelaCadastroCliente">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>CPF</th>
                    <th>Endereço</th>
                    <th>Número</th>
                    <th>Bairro</th>
                    <th>CEP</th>
                    <th>UF</th>
                    <th>Cidade</th>
                    <th>Distrito</th>
                    <th id="acao">Ação</th>
                </tr>
            </thead>
            <td>Wesley Vicente</td>
            <td>11951606400</td>
            <td>Praça Joaquim Nabuco</td>
            <td>10</td>
            <td>Centro</td>
            <td>55850-000</td>
            <td>PE</td>
            <td>Vicência</td>
            <td>Vicência1</td>
            <td class="remover">Remover</td>
            <tfoot>

                <td colspan="10">Isso é tudo</td>
            </tfoot>
        </table>
    </main>

  • Very good guy, solved in addition what I was looking for and got more streamlined the code.

  • That’s good. You should choose the best answer you found and score.

Browser other questions tagged

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