Home > Mobile >  Delete row using inout field
Delete row using inout field

Time:11-08

I am creating table, and want to remove row by id using input field. (if input field matches with id then the row must be deleted) can not figure it out.

Your help is much appreciated `

<body onl oad="addRow()">
<table id="myTable" style="display:none">
    <tr>
        <th >ID</th>
        <th>Name</th>
        <th>Username</th>
        <th>Gender</th>
        <th>Country</th>
    </tr>
    <tbody id="myTableBody">
    </tbody>
</table>
<button type="button" id="buttonShow" onclick="showTable()">Show Table</button>
<button type="button"  id="buttonAdd" onclick="addRow()" disabled>Add a new row</button>
<br>
<label>
    <input   type="text" name="todoTags"/>
    <button  id="buttonDell"onclick="delRow()" disabled>Delete row</button>
</label>

`

`

    function showTable(){
        document.getElementById("myTable").style.display = "block";
        document.getElementById("buttonAdd").disabled = false;
        document.getElementById("buttonDell").disabled = false;
    }
    const btn = document.querySelector('.dellbtn')
    const userTags = []

` Here is my: JSfiddle

CodePudding user response:

Not exactly what you're asking, but this method might work better for you. It uses a delete button for each row so you can decide which one to delete. Then it uses a delegate listener to enable the delete buttons

const table = document.querySelector('#theTable tbody');
let c = 1
const addRow = () => {
  table.innerHTML  = `<tr><td>${c} data</td><td>${c}  data</td><td><button class='delete'>delete</button></td></tr>`;
  c  
}

// delegate listener for the delete button
table.addEventListener('click', e => {
  if (e.target.classList.contains('delete')) {
    e.target.closest('tr').remove();
  }
})
<table id='theTable'>
  <th>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
      <td></td>
    </tr>
  </th>
  <tbody>
  </tbody>
</table>

<button onclick='addRow()'>Add Row</button>

CodePudding user response:

What you could do is changing the addRow() method so it adds a data-attribute to each row, in the <tr>. You can achieve this goal by adding this when creating the row :

row.setAttribute("row-id", tr.length - 1);

Then, when you want to delete it, you can simply search the row that has the data-attribute that you just input. And it will look like this :

  function delRow() {
        const value = document.getElementById("valueToDelete").value;
        document.querySelector('[row-id="'   value   '"]').remove();
    }

I created a fork to your JSFiddle that you can check right here.

Hope it helps ! Good luck :)

  • Related