How do I return a relative HTML table value?

Viewed 48

I have an HTML table with buttons in the fourth column. I want to be able to push each button and have it return the value in the second column, but same row.

I create the table using this code:

function loadTableData() {
    for (i=0; i < 7; i++) {
        let row = table.insertRow();
        let scale = row.insertCell(0);
        let note = row.insertCell(1);
        let chord = row.insertCell(2);
        let play = row.insertCell(3);
        scale.innerHTML = degChoice[i]
        note.innerHTML = finalArray[i];
        chord.innerHTML = chordChoice[i];
        play.innerHTML = '<button onclick="playAudio()">Play Chord</button>'
    }
}

The table values are being generated based on other criteria (this part's working fine).

And this is the code I am using to try to call the value of the second cell in the row:

function playAudio(){
    var firstCell = this.parentNode.parentNode.childNodes[1].nodeValue;
    alert(firstCell);
}

No matter what I try, I can't return that second cell value. Does anyone have any advice for this?

1 Answers

You are assigning the event handler wrong. Generally you should avoid using on... attributes, but if you do it, you need to pay attention to how this is assigned a value.

It is defined inside the onclick, but not inside your function playAudio, so you will need to pass it on:

play.innerHTML = '<button onclick="playAudio(this)">Play Chord</button>'
function playAudio(button){
  var firstCell = button.parentNode.parentNode.childNodes[1].nodeValue;
  alert(firstCell);
}

However alternativly you can use this inside playAudio if you assign it directly as the event handler, but then you'll need to create the button as a DOM element:

const button = document.createElement("button");
button.textContent = "Play Chord"; // Use textContent instead of innerHtml when assigning plain text
button.addEventListener("click", playAudio); // or: button.onclick = playAudio;
play.appendChild(button);

Now you can use this inside playAudio. Or, even better access the event object as the first parameter inside playAudio:

function playAudio(event){
  var button = event.target; // or: var button = this;
  var firstCell = button.parentNode.parentNode.childNodes[1].nodeValue;
  alert(firstCell);
}

Intoduction to events: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Related