Nanda
Nanda

Reputation: 173

How to add table rows when button clicked: jquery

I have a template which contains two add buttons and two tables. When user clicks add button rows should append to the respective table. Example:

<div class="reports">
   <div class="panel">
    <table class="A">
     <thead>
      <td>A</td>
      <td>B</td>
      <td>C</td>
     </thead>
     <tbody></tbody>
    </table>
   </div>
   <button class="add" type="button">Add</button>
  </div>

Am using same code for creating table and add button with different ids report.js is

$('.reports').on('click','.add',function(){
      //do something
});

I want rows to be appended to the respective table.

Upvotes: 1

Views: 421

Answers (3)

AmmarCSE
AmmarCSE

Reputation: 30557

Use append()

$('.reports').on('click','.add',function(){
      $(this).closest('.reports').find('table').append('<tr/>');
});

Upvotes: 4

Gautam
Gautam

Reputation: 255

Assuming you have different ids at parent divs

$('.reports').on('click','.add',function(){
    $(this)  //button that was clicked
   .parent() //div around the button
     .siblings(".A")  //sibling element that has the table
       .find("table tbody")  //the table
         .append(tableRow);

Upvotes: 1

Vontei
Vontei

Reputation: 1897

The vanilla Js approach:

var button = document.getElementsByClassName('add');
var table = document.getElementsByClassName('A');

button.addEventListener('click', function(){
  var tr = document.createElement('tr');
  table.appendChild(tr);
});

Upvotes: 1

Related Questions