0

I'm creating multiple tables from one table (table id = table6) If I created a new table from table id ='table6', I want to delete that newly generated table using its table id. I have assigned table ids to the newly generated tables. what's wrong in my code? I want to delete this HTML table. Any hint?

var aggTableNum = 0;

function generateAgg() {
  const originTable = document.getElementById('table6');
  const baseRowTbl = originTable.querySelector('tbody tr');
  let newTable = originTable.cloneNode(true);
  let newTbody = newTable.querySelector('tbody');
  newTable.id = 'newAggTable' + ++aggTableNum;
  // for (i = 0; i < 0; i++) {
  //   newTbody.appendChild(baseRowTbl.cloneNode(true));
  // }
  newTable.querySelectorAll('input').forEach((element) => {
    element.value = '';
  });
  document.body.appendChild(newTable);
}

function tID() {
  $('table').on('click', 'button', function (e) {
    alert(e.delegateTarget.id);
     var tbl = e.delegateTarget.id;
    console.log(tbl);
    // if (tbl) tbl.parentNode.removeChild(tbl);
    $(tbl).remove(); 
  });
}
table {
  border-collapse: collapse;
  margin: 1em;
}
thead {
  background-color: lightblue;
}
td,
th {
  border: solid grey 1px;
  padding: 1em;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin: 1%" onclick="generateAgg()">Generate New Table</button>
<table id="table6">
        <thead>
          
        <th colspan="6">Table</th>
    
        <tr>
          <th> Column 1 </th>
          <th> Column 2 </th>
         
      
        </tr>
        </thead>
        <tbody>
        <tr>
      
          <td>
            <input>
            </input>
          </td>
          <td><input>
            </input></td>
    
        </tr>
        <tr>
     
        <td>
          <button style="margin: 1%" onclick="tID()">delete </button>
        </td>
      </tr>
      </tbody>
      </table>

JsFiddle link - > https://jsfiddle.net/shreekantbatale2/hn0286zd/8/

2
  • Did you debug the code using the debugger keyword? and check why on button onclick, jquery $('table').on('click' event handler was not called? Commented Apr 26, 2020 at 15:54
  • 3
    It should be $("#" + tbl).remove(); Working Fiddle: jsfiddle.net/gr1cpjbo Commented Apr 26, 2020 at 15:55

1 Answer 1

1

Though you are getting the table id's value, need to refer that properly with jquery with a leading # in the selector.

Change this:

$(tbl).remove(); 

...to:

$('#' + tbl).remove(); 

Then the table removes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.