0

I need to be creating this table dynamically. I am currently using JQuery and a function (expandTable) that expands the table based on clicking on anywhere in the row. Is there a way to do this by just clicking on the button?

buildTable(3);
expandTable();

function expandTable() {
  $('.header').click(function() {
    $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
  });
}

function buildTable(data1) {
  var table = document.getElementById('myTable');
  var row = '';


  for (var i = 0; i < data1; i++) {
    row += `<tr class ="header">
                            <th> <button> + </button> row ${i} </th>
                        </tr>
                        <tr style="display: none;">
                            <td> Expandable for row ${i} </td>
                        </tr>`;
  }
  table.innerHTML += row;
}
td {
  text-align: left;
  font-size: 14px;
  border: 1px solid black;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
  <tbody id="myTable">
  </tbody>
</table>
  • Does this answer your question? [Simplest way to detect keypresses in javascript](https://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript) – ikiK Aug 02 '21 at 14:39

1 Answers1

1

In your expandTable function, you can change the jQuery selector to this to target the button:

$('.header>th>button')

Then you can traverse back up the DOM to to target the the <tr> with the jQuery .closest() selector.

See snippet below.

buildTable(3);
expandTable();

function expandTable() {
  $('.header>th>button').click(function() {
    $(this)
      .closest(`tr`)
      .toggleClass('expand')
      .nextUntil('tr.header')
      .slideToggle(400);
  });
}

function buildTable(data1) {
  var table = document.getElementById('myTable');
  var row = '';

  for (var i = 0; i < data1; i++) {
    row += `<tr class ="header">
                <th> <button> + </button> row ${i} </th>
            </tr>
            <tr style="display: none;">
                <td> Expandable for row ${i} </td>
            </tr>`;
  }
  table.innerHTML += row;
}
td {
  text-align: left;
  font-size: 14px;
  border: 1px solid black;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<table>
  <tbody id="myTable">
  </tbody>
</table>
Steve
  • 878
  • 1
  • 5
  • 9