-2

I wonder whether I can insert rows in html talbe by clicking them.

For example when I prepare this table like below, and by clicking them

    <table>
      <tbody>
        <tr>
          <td>0</td>
          <td>1</td>
          <td>2</td>
        </tr>
      </tbody>
    </table>

My desired result is like this. And I would like to know how to add any rows by clicking

<table>
      <tbody>
        <tr>
          <td>0</td>
          <td>1</td>
          <td>2</td>
        </tr>
           <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        .
        .
        .
        .
   </tbody>
  </table>

If someone has opinion, please let me know.

Thanks

table {
border-collapse:collapse;}

td {
border:solid black 1px;
transition-duration:0.5s;
padding: 5px}
<table>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>
Heisenberg
  • 4,787
  • 9
  • 47
  • 76

3 Answers3

3

You could do it like this:

$(document).ready(function() {
   $("table").on( "click", "tr", function() {
       $("table").append($(this).clone());
   });
});

Note that it's necessary to pass the event from a parent element that's already there when the page is initially loaded - table - to all tr-elements using on().
jQuery on()

matthias_h
  • 11,356
  • 9
  • 22
  • 40
1

If you simply want to create new tr elements and add them to the table when it's clicked, you could simply create a click event handler to do so. For example:

// Store DOM elements in some variables
const [tbodyEl] = document.querySelector('table').children;
const [trEl] = tbodyEl.children;

// Create an event handler function
const sppendAdditionalRowToTable = e => {
  const newTrEl = document.createElement('tr');


  for (let i = 0; i < 3; i += 1) {
    newTrEl.appendChild(document.createElement('td'));
  }

  tbodyEl.appendChild(newTrEl);
};

// Call handler function on click event
tbodyEl.addEventListener('click', sppendAdditionalRowToTable);
table {
  border-collapse: collapse;
}

td {
  border: solid black 1px;
  transition-duration: 0.5s;
  padding: 5px
}
<table>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>
Tom O.
  • 5,730
  • 2
  • 21
  • 35
0

This works:

$( document ).ready(function() {
  $('#tableID').on( "click", "tr", function() {
    $("tbody").append("<tr><td>0</td><td>1</td><td>2</td></tr>");
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="tableID">
      <tbody>
        <tr>
          <td>0</td>
          <td>1</td>
          <td>2</td>
        </tr>
      </tbody>
    </table>
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41