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 = e.target;
               while( (td = td.previousElementSibling) != null ) 
                   j++;
               alert(rows[1].cells[j].innerHTML);
           });
       }

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" >
 <thead>
 <tr class="info">
   <th>Group Name</th>
   <th>User Group</th>

 </tr>
 </thead>
 <tbody id="table_body">
 <br>
 
   <% @array.each do |user| %>
   <tr>
   
     <td >
       <%=user['group_name']%>
     </td>
       <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>
       </td>
        
     <% end %>
   </tr>
 </tbody>
 </table>

Answer

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);
        console.log(rowid);
    })
});
<table id="user_table">
    <tr>
        <th>Group name</th>
        <th>Manage group</th>
    </tr>
    <tbody>
    <tr>
        <td>Test 1</td>
        <td><button>Button</button></td>
    </tr> <tr>
        <td>Test 2</td>
        <td><button>Button</button></td>
    </tr>
    </tbody>
</table>

Leave a Reply

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