2

Need help with populating a text area based on html table row selection.

In the table below, I want to extract the content of the column 'Comments' for the selected row and write into the text area 'Comment' on the same page. I have only managed to create the table but nothing else.

enter image description here

Below is the code I have now created from this link. What is happening now is that only the currently selected cell gets put in the text box instead of just the 'Comment' column. I want to input only in the 'Comment' column into the box regardless of the cell clicked upon in the row.

<table id="table">
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Comments</th>
        </tr>
   <tbody>
        <tr>
            <td>John</td>
            <td>42</td>
            <td>avery long comment</td>
        </tr>
        <tr>
            <td>Peter</td>
            <td>35</td>
            <td>another very long comment</td>
        </tr>
        <tr>
            <td>Mary</td>
            <td>54</td>
            <td>some comment</td>
        </tr>
   </tbody>
</table>


<script>
   var table = document.getElementById('table');
   var selected = table.getElementsByClassName('selected');
   table.onclick = highlight;

   function highlight(e) {
    if (selected[0]) selected[0].className = '';
    e.target.parentNode.className = 'selected';
   
    var element = document.querySelectorAll('.selected');
    if (element[0] !== undefined) { //it must be selected
        document.getElementById("myTextbox").value = element[0].children[0].firstChild.data
    }        
   }
</script>


<div >
    <textarea class="form-control" id="myTextbox"></textarea>  
</div> 

Thanks for your help.

ibexy
  • 609
  • 3
  • 16
  • 34

1 Answers1

0

You're getting the first column but you can get the third column with the comment by changing the index of the child to 2 instead of 0.

document.getElementById("myTextbox").value = element[0].children[2].firstChild.data
tomasantunes
  • 814
  • 2
  • 11
  • 23