Home > Net >  How to delete HTML column with dynamic header <th> name
How to delete HTML column with dynamic header <th> name

Time:10-16

I have a script that able to add new column to a HTML table. When user press add group the header will become Group1, Group2 and so on.. Currently im adding a delete group function that able to delete all the added column. So now the problem is when I delete a column and add again a new column , the name Group(x) will not be reset.

For example:user add group1 and group2 after that he delete group2. The next time he press add group again, it will show group3 instead of group2 Image:

enter image description here

Expected Output: The column name should be reset whenever the column is deleted.

Html:

<table id="persons" border="1">
    <thead id="theadID">
        <tr>
            <th>Name</th>
            <th>sex</th>
            <th>Message</th>
        </tr>
    </thead>
    <tbody id="tbodyID">
        <tr>
            <td>Viktor</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Melissa</td>
            <td>Female</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Joe</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>

<button onclick="javascript:appendColumn()">Add column</button>

<input type="button" onclick="deleteLastColumn();" value="do it"/>

Jquery& Javascript:

function deleteLastColumn() {
    $('#persons tr').find('th:last-child, td:last-child').remove()
}


        let groupNum = 1;
const tableEl = document.getElementById('persons');

// append column to the HTML table
function appendColumn() {

  // open loop for each row and append cell
  for (let i = 0; i < tableEl.rows.length; i  ) {
    createCell(tableEl.rows[i].insertCell(tableEl.rows[i].cells.length), i, 'col');
  }

  tableEl.rows[0].querySelector('td:last-child').textContent = 'Group'   groupNum;
  groupNum  ;
}

// create DIV element and append to the table cell
function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode(text); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('class', style); // set DIV class attribute
  div.setAttribute('className', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}


CodePudding user response:

maybe I'm missing it but I don't see the code which deletes ALL the cols, I only see one. But still the solution seems simple, just decrement the groupNum variable when you delete a col

function deleteLastColumn() {
    $('#persons tr').find('th:last-child, td:last-child').remove()
    groupNum--;
}
  • Related