abrahamlinkedin abrahamlinkedin - 3 months ago 9
Javascript Question

setting functions for dynamically generated table

I have a table with dynamically generated content. Each row comes with a button that is meant to serve that row. In my case I want my button's outerHTML to adopt the name of the name on its row.

I am having trouble assigning

this
to my onclick event. As is, clicking either button will only repeat the name on the first row. I am unsure of the exact proper syntax for getting the button to change to its appropriate row name.



var erray = ["Todd", "Bill", "Sam"];
var pname = document.querySelectorAll('.pname');
var adoptname = document.querySelectorAll('.adoptname');

for (var i = 0; i < erray.length; i++){
var adoptname = document.querySelectorAll('.adoptname');
pname[i].innerText = erray[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>




Answer
<table>
<thead><tr>
<th>Name</th>
<th>Adopt</th>
</tr></thead>
<tbody id="table_body">
<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>

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>

<script>
window.onload=function()
{
  var array=["Todd","Bill","Sam"];

  for(var i=0;i<array.length;i++)
  {
     $("#table_body tr:nth-child("+(i+1)+") .pname").html(array[i]);
     $("#table_body tr:nth-child("+(i+1)+") .adoptname").attr("id","adopt-"+array[i]);
  }


  $("#table_body").on("click","[id^=adopt]",function(){
         var id=$(this).attr("id");
         var name=id.split("-")[1];
         alert(name);
  });
  }

 </script>