简体   繁体   中英

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

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 class=" animated bounceInUp">
        <td >${t.Name}</td>
        <td >${t.Email}</td>
        <td >${t.Contacts}</td>
        <td >${t.Address}</td>
        <td >${t.Country}</td>
        <td ><button class="btn btn-success btn-xs" 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);
      }
      }

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 class="email">salvino@example.com</td> <td><button onclick="getEmail(this)">Button</button></td> </tr> <tr> <td>Someone</td> <td class="email">someone@example.com</td> <td><button onclick="getEmail(this)">Button</button></td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM