-1
I’m creating a very simple dynamic table. Working to include the data, but I don’t know how to remove only the line I clicked on on the button delete. I made a function deletar()
but she searches for ID
of the entire table and ends up deleting the table altogether.
function deletar() {
var linha = document.getElementById('campo');
linha.remove();
}
I have no idea how I could do to delete just the clicked line?
Follow the full code:
var teste = 0;
function salvarDados(){
var nome = document.getElementById("nome").value;
var valor = document.getElementById("valor").value;
var vencimento = document.getElementById("vencimento").value;
if (!(nome == '' || valor == '' || vencimento == '')) {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var btn = document.createElement("button");
td1.innerHTML = nome;
td2.innerHTML = valor;
td3.innerHTML = vencimento;
btn.innerHTML = "deletar";
btn.onclick = deletar;
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(btn);
tr.id = 'linha' + teste;
teste++;
document.getElementById("campo").appendChild(tr);
limparCampos();
}else {
alert('Todos os campos precisam estar preenchidos !!');
}
}
function limparCampos(){
var nome = document.getElementById("nome");
var valor = document.getElementById("valor");
var vencimento = document.getElementById("vencimento");
nome.value = '';
valor.value = '';
vencimento.value = '';
}
function deletar(teste2) {
var linha = document.getElementById('campo');
linha.remove();
}
<body>
Nome: <input type="text" id="nome">
Valor: <input type="number" step="any" id="valor">
Vencimento: <input type="date" id="vencimento">
<button id="botao-salvar" onclick="salvarDados()">Salvar</button>
<table border="1" id="campo">
<legend>Contas a Pagar</legend>
<tr>
<th>Nome</th>
<th>Valor</th>
<th>Vencimento</th>
</tr>
</table>
</body>
I added a way to assign ID to each line that is added. com
tr.id = 'linha' + teste;
teste++;
But I still can’t find the selected ID and just delete that line.
Thanks friend, helped a lot !! Solved my doubts and my problem.
– Gabriel Branger