establishing functionality for a table that is created dynamically

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>

Answer №1

Imagine you have the following HTML structure:

<table>
   <thead>
       <th>Name</th>
       <th>Action</th>
   </thead>

   <tbody id="table_body">
   </tbody>
</table>

Now let's take a look at the JavaScript code:

var names=["Alice","Bob","Charlie"];
var html="";

for(var i=0;i<names.length;i++)
{
   html += "<tr><td>"+names[i]+"</td><td><button id=\"action-"+names[i]+"\">Do Action</button>";
}

$("#table_body").html(html);

Next, examine the click event functionality:

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

Answer №2

<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=["Ella","Max","Lily"];

  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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you locate the position of identified text on a webpage to accurately place the mouse cursor there?

When browsing a webpage in my web browser (preferably Firefox), I have the ability to search for a specific text "abc" using ctrl+f. Once found, I need to move my mouse cursor to another relative position on the page and click. Unfortunately, the necessar ...

The corresponding Javascript method for jquery's ajaxStop

Currently, I have numerous ajax requests running concurrently and I would like to trigger a function once they all have completed. I came across the jQuery function: ajaxStop(), however, I am unable to utilize jQuery in this particular project. Is there ...

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

Unable to invoke function within class using 'this'

I've been working on a class named Scheduler that runs a cron job using the cron module. I've defined a function to calculate the difference in days between two dates, and it works fine when called outside of the cron job iteration. However, if I ...

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...

Adding a Div dynamically to an HTML page with the help of JavaScript or jQuery

Is there a way to create a main div and then dynamically add new divs at the same level as the main div? Here's an example of what I'm looking for: <div id="main"></div> <div id="created_div"></div> I would greatly appre ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

What is the best way to effectively apply chunking and batching when working with a group of promises or async functions?

When processing a large collection of async functions in batches, I am presented with two different scenarios: Scenario 1: Gathering all the async functions import { chunk } from "lodash"; const func = async () => new Promise((resolve) =& ...

What is the reason behind a Handler-Function only functioning anonymously in electron/node.js?

Have you ever wondered why it's possible to write something like this in node (electron): app.on('ready', function() { mainWindow = new BrowserWindow({ width: 800, height: 480 }); }); But when attempting this, i ...

Ways to create distance between repeated cards in a loop. My method involves utilizing ajax, jquery, and bootstrap

view image description here What is the best way to create some space between these closely aligned cards? .done((todos) => { todos.forEach(el => { console.log(el) $("#todo-list").append(` <d ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

What sets srcset apart from media queries?

Can you explain the contrast between srcset and media query? In your opinion, which is more optimal and what scenarios are ideal for each? Appreciate it! ...

Tips for creating a double-layered accordion list within another accordion list:

I am currently utilizing this example to create an accordion list, but I require a two-level accordion list. It should look something like this: -Group -Child1 Child2 Child2 +Child1 +Child1 +Group +Group For reference, you can check it ou ...

Changing various $scope object properties using ng-model

Can you help me figure out why the $scope.data variable is not updating when I input valid values in the form fields? How can I solve this issue? Check out the code example on Codepen: http://codepen.io/uloco/pen/jboorN HTML <div ng-app="app" ng-contr ...

Save the file to a specific folder and compress the entire folder into a

I have encountered an issue while attempting to write a file to a directory named templates and then stream a zip file with the content that was just written. The problem arises when the zip file is returned, displaying an error message "Failed - Network E ...

Using PHP and Ajax to pass parameters in Javascript

I have a PHP code that triggers a JavaScript function: onclick='fightit(0,0,0,0,0)' This is the JavaScript function: function fightit(nbr,strt,bar,type,action) { var params = "Nbr="+nbr; params += "&Strt="+strt; params += "&Bar="+bar; ...

Problem encountered when private parameters do not match in the constructor

TL:DR: encountering an error Supplied parameters do not match any signatures of call target when trying to utilize private constructor parameters like constructor (private http: Http) {} Running into difficulty while configuring private parameters in Angu ...

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...

Click once to open the JS menu, and click again to be redirected to the URL

I am attempting to design a dropdown menu that will reveal the child elements upon first click. When clicking on a child element, it should navigate to the child's URL. Clicking on the country name again should collapse the child menu. Although I hav ...

Searching for data in datatables can be done by utilizing the data loading functionality with ajax or serverside processing

Hello there, I'm relatively new to using datatables and I've encountered an issue. Whenever I type something into the search field of my table, the 'processing' loading label pops up. I load my data via ajax in the table. So, what steps ...