Get table row value based on button click using Jquery/Javascript

I need to get the table row value from onclick event. Below the table, I am using

Group name|Manage group

Test 1    | Button

Test 2    | Button

If I click ‘Button’ from the table row, I need to get the respective group name value from the table row.

Below the script, I am trying. But it is printing only the first group name value “Test 1” for both buttons.

var table = document.getElementById("user_table");
       var rows = table.rows;
       for (var i = 1; i < rows.length; i++) {
           rows[i].onclick = (function (e) {
               var rowid = (this.cells[0].innerHTML);
               var j = 0;
               var td =;
               while( (td = td.previousElementSibling) != null ) 

alert(rows[1].cells[j].innerHTML) printing group name value Test 1 and if I click second row button it is showing Test 1 only.But I need to get Test 2 if I click second row button.

Html file

<table id="user_table"  style='overflow-x:scroll;overflow-y:scroll;width:100%;height:auto' class="table table-bordered" >
 <tr class="info">
   <th>Group Name</th>
   <th>User Group</th>

 <tbody id="table_body">
   <% @array.each do |user| %>
     <td >
         <button id='manageusrbtn' name="button" type="button" class="editbtn" onclick="manageUserGroups()" style="background-color: #008CBA; color: white; border-radius: 6px;" >Manage User Groups</button>
     <% end %>


I would suggest to attach the click event handler to the button and not to each cell. For this you can use:

The snippet:

var table = document.querySelectorAll('#user_table tr button');
table.forEach(function(ele) {
    ele.addEventListener('click', function (e) {
        var rowid = (this.closest('td').previousElementSibling.innerHTML);
<table id="user_table">
        <th>Group name</th>
        <th>Manage group</th>
        <td>Test 1</td>
    </tr> <tr>
        <td>Test 2</td>

Leave a Reply

Your email address will not be published. Required fields are marked *