Home > Software design >  JavaScript Getting second <td> cell value when clicked on a button on the same row
JavaScript Getting second <td> cell value when clicked on a button on the same row

Time:12-11

How can I get email cell value when I click on the button which is located at the last cell of the same row.

Please check this screenshot for better understanding what I mean

So when I click Button 1, I want to get Email1 value or when click Button 2, I want to get N2 cell value.

My HTML Mockup:

function renderCustomers(tasks) {
customerList.innerHTML  = `
    <tr >
        <th >Name</th>
        <th >Email</th>
        <th >Contacts</th>
        <th >Address</th>
        <th >Country</th>
        <th >Action</th>
    </tr>`;    
tasks.forEach((t) => {
  customerList.innerHTML  = `
    <tr >
        <td >${t.Name}</td>
        <td >${t.Email}</td>
        <td >${t.Contacts}</td>
        <td >${t.Address}</td>
        <td >${t.Country}</td>
        <td ><button  id="getCustomerEmail">
            Get Customer Email
        </button></td>
    </tr>`;
});

}

I found this function but it return the clicked cell value not the one I need:

  function getElementID(){
    var tbl = document.getElementById("Results");
  if (tbl != null) {
      for (var i = 0; i < tbl.rows.length; i  ) {
          for (var j = 0; j < tbl.rows[i].cells.length; j  )
              tbl.rows[i].cells[j].onclick = function () { getval(this); };
      }
  }
  function getval(cel) {
      alert(cel.innerHTML);
  }
  }

Any help is really appreciated

I found this function but it return the clicked cell value not the one I need:

function getElementID(){
   var tbl = document.getElementById("MyTable");
   if (tbl != null) {
      for (var i = 0; i < tbl.rows.length; i  ) {
         for (var j = 0; j < tbl.rows[i].cells.length; j  )
             tbl.rows[i].cells[j].onclick = function () { getval(this); };
          }
      }
    function getval(cel) {
        alert(cel.innerHTML);
      }
      }

CodePudding user response:

I think you simply bind a class to your td and then reference it based on the context of the clicked button.

function getEmail(el) {
  const tr = el.closest('tr');
  const tds = tr.getElementsByClassName('email');
  console.log(tds[0].innerHTML);
}
<table>
  <thead>
    <th>Name</th>
    <th>Email</th>
    <th>Action</th>
  </thead>
  <tbody>
  <tr>
    <td>Salvino</td>
    <td >[email protected]</td>
    <td><button onclick="getEmail(this)">Button</button></td>
  </tr>
  <tr>
    <td>Someone</td>
    <td >[email protected]</td>
    <td><button onclick="getEmail(this)">Button</button></td>
  </tr>
  </tbody>
</table>

  • Related