Skip to content
Advertisement

How can I use JavaScript to delete a row in an HTML table and its associated data when a button is clicked?

How can I use JavaScript to delete a row in an HTML table and its associated data when a button is clicked? What is the most efficient way to identify the row to be deleted, and what method should I use to remove the row from the DOM? Additionally, how can I ensure that the deletion of the row does not affect the styling or functionality of the remaining rows in the table?

When I click on the button: Remover, the line is hidden. When I click the Adicionar button again, the line that was hidden is added. I want the line along with the data to be definitively deleted when I click on the button: Remover.

I’ve tried using several methods and I can’t solve it, can anyone help?

const form = document.getElementById("agenda-de-contatos");
let linhas = "";

form.addEventListener("submit", function (e) {
  e.preventDefault();

  const inputNomeContato = document.getElementById("nome-do-contato");
  const inputNumeroTelefone = document.getElementById("numero-de-telefone");

  let linha = "<tr>";
  linha += `<td>${inputNomeContato.value}</td>`;
  linha += `<td>${inputNumeroTelefone.value}</td>`;
  linha += `<td><button class='excluir' onclick="deleteRow(this.parentNode.parentNode.rowIndex)">Remover</button></td>`;
  linha += "</tr>";

  linhas += linha;

  const corpoTabela = document.querySelector("tbody");
  corpoTabela.innerHTML = linhas;
});

function deleteRow(id) {
  document.getElementById("tabela").deleteRow(id);
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
}

body {
    background-color: #e7e7e7;
    padding-top: 100px;
}

header {
    display: flex;
    align-items: center;
    margin-bottom: 40px;
}

header img {
    height: 36px;
    margin-right: 16px;
}

header h1 {
    font-size: 40px;
    font-weight: bold;
}

.container {
    max-width: 960px;
    width: 100%;
    margin: 0 auto;
}

form {
    display: flex;
    max-width: 640px;
    width: 100%;
    justify-content: space-around;
    margin-bottom: 56px;
}

form input {
    font-size: 16px;
    background-color: #fff;
    border: none;
    border-bottom: 2px solid #000;
    padding: 16px;
    margin: 0 auto;
}

form button {
    background-color: #297fc3;
    color: #fff;
    font-size: 16px;
    font-weight: bold;
    border: none;
    cursor: pointer;
    padding: 16px;
    margin: 0 auto;
}

table {
    width: 100%;
}

table th {
    border-bottom: 2px solid #000;
    padding: 16px;
    font-size: 24;
    font-weight: bold;
}

table td {
    padding: 16px 0;
    text-align: center;
    font-size: 18px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

table td img {
    height: 30px;
}

button:hover {
    background-color: #258ddd;
}

input:focus,
textarea:focus {
    outline-color: #297fc3;
}
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">

<div class="container">
  <header>
    <img src="./images/contatos.png" alt="agenda de contatos" />
    <h1>Agenda de contatos</h1>
  </header>
  <form id="agenda-de-contatos">
    <input type="" id="nome-do-contato" required placeholder="Nome do contato" />
    <input
      type="tel"
      id="numero-de-telefone"
      pattern="((?[0-9]{2})?)([0-9]{4,5})-?([0-9]{4})"
      required
      placeholder="Telefone (xx) xxxx-xxxx"
      title="Número de telefone precisa ser no formato (xx) xxxx-xxxx"
      required="required"
    />
    <button type="submit">Adicionar</button>
  </form>
  <table id="tabela" cellspacing="0">
    <thead>
      <tr>
        <th>Nome do contato</th>
        <th>Número de telefone</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

Advertisement

Answer

The issues is you are storing the all the generated html in linhas which is a string and when deleting you never removed the from this variable. I have converted this to array so that we can delete the row.

const form = document.getElementById('agenda-de-contatos');
let linhas = [];

form.addEventListener('submit', function (e) {
    e.preventDefault();
    const inputNomeContato = document.getElementById('nome-do-contato');
    const inputNumeroTelefone = document.getElementById('numero-de-telefone');

    let linha = '<tr>';
    linha += `<td>${inputNomeContato.value}</td>`;
    linha += `<td>${inputNumeroTelefone.value}</td>`;
    linha += `<td><button class='excluir' onclick="deleteRow(this.parentNode.parentNode.rowIndex,this)">Remover</button></td>`;
    linha += '</tr>';

    linhas.push(linha);

    const corpoTabela = document.querySelector('tbody');
    corpoTabela.innerHTML = linhas.join()
})

function deleteRow(id,node) {
 linhas.splice(id-1,1);
    document.getElementById('tabela').deleteRow(id);
  
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
}

body {
    background-color: #e7e7e7;
    padding-top: 100px;
}

header {
    display: flex;
    align-items: center;
    margin-bottom: 40px;
}

header img {
    height: 36px;
    margin-right: 16px;
}

header h1 {
    font-size: 40px;
    font-weight: bold;
}

.container {
    max-width: 960px;
    width: 100%;
    margin: 0 auto;
}

form {
    display: flex;
    max-width: 640px;
    width: 100%;
    justify-content: space-around;
    margin-bottom: 56px;
}

form input {
    font-size: 16px;
    background-color: #fff;
    border: none;
    border-bottom: 2px solid #000;
    padding: 16px;
    margin: 0 auto;
}

form button {
    background-color: #297fc3;
    color: #fff;
    font-size: 16px;
    font-weight: bold;
    border: none;
    cursor: pointer;
    padding: 16px;
    margin: 0 auto;
}

table {
    width: 100%;
}

table th {
    border-bottom: 2px solid #000;
    padding: 16px;
    font-size: 24;
    font-weight: bold;
}

table td {
    padding: 16px 0;
    text-align: center;
    font-size: 18px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

table td img {
    height: 30px;
}

button:hover {
    background-color: #258ddd;
}

input:focus,
textarea:focus {
    outline-color: #297fc3;
}
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agenda de contatos</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>

<body>
    <div class="container">
        <header>
            <img src="./images/contatos.png" alt="agenda de contatos">
            <h1>Agenda de contatos</h1>
        </header>
        <form id="agenda-de-contatos">
            <input type="" id="nome-do-contato" required placeholder="Nome do contato">
            <input type="tel" id="numero-de-telefone" pattern="((?[0-9]{2})?)([0-9]{4,5})-?([0-9]{4})" required
                placeholder="Telefone (xx) xxxx-xxxx" title="Número de telefone precisa ser no formato (xx) xxxx-xxxx"
                required="required"></br>

            <button type="submit">Adicionar</button>
        </form>
        <table id="tabela" cellspacing="0">
            <thead>
                <tr>
                    <th>
                        Nome do contato
                    </th>
                    <th>Número de telefone</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <script src="./main.js"></script>
</body>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement