[Solved] How to pass html table cell value to javascript variable?


This code

  1. Adds a click (event) listener to every first <td> of every <tr>
  2. On click the text is parsed to int (base10), and the number is passed to the handler function (getNumber(val))
  3. The handler function prints the value read from the <td> to the console
// "grabbing" each row
const rows = document.getElementsByTagName('tr')

// iterating over each row
for (let i = 0, length = rows.length; i < length; i++) {

  // grabbing the first child element in each row (so no text
  // or other type of nodes - only elements)
  // then adding a click event listener with a callback function
  rows[i].firstElementChild.addEventListener('click', function(e) {

    // calling the "designed" function in the event listener
    // callback
    getNumber(parseInt(this.textContent, 10))
  })
}

// the handling function
function getNumber(val) {
  console.log(val)
}
td:first-child {
  cursor: pointer;
  font-weight: 700;
}
<table>
  <tr>
    <td>1</td>
    <td> The Fratellis - Chelsea Dagger </td>
  </tr>
  <tr>
    <td>2</td>
    <td> Connect Northants: Eternal / Bebe Winans - I Wanna Be The Only One</td>
  </tr>
  <tr>
    <td>3</td>
    <td> Virgin_UK_128</td>
  </tr>
</table>

1

solved How to pass html table cell value to javascript variable?