I have a dynamic table with unique content in each row. Each row has a button that is specific to that row. I want the outerHTML of the button to display the name of the corresponding row.
Currently, I am struggling to assign 'this' properly to the onclick event. Presently, when clicking any button, it only displays the name from the first row. I need help figuring out the correct syntax to ensure that each button shows the correct name associated with its row.
var names = ["Todd", "Bill", "Sam"];
var pname = document.querySelectorAll('.pname');
var adoptname = document.querySelectorAll('.adoptname');
for (var i = 0; i < names.length; i++){
var adoptname = document.querySelectorAll('.adoptname');
pname[i].innerText = names[i];
adoptname[i].onclick = adoption;
function adoption(){
for (var i = 0; i < pname.length; i++)
this.outerHTML = pname[i].innerHTML;
}
}
table { border: 1px solid black; }
<table>
<thead><tr>
<th>Name</th>
<th>Adopt</th>
</tr></thead>
<tbody>
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
</tbody>
</table>