JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specific button that was clicked to the event handler is necessary in order to identify which one needs to be deleted.

When hardcoding, I typically pass 'this' to the event handler. How can I achieve this same functionality when generating dynamic buttons?

At the moment, my code looks like this:

{
var cell0 = row.insertCell(0);
var btn = document.createElement("input");
btn.type = "button";
btn.id = "btnHistorySelect_" + roundHdr[i].id;              // appending the id to the name allows us to reference it when the select button is clicked, thus indicating the current round to select
btn.value = "Set Current";
btn.onclick = btnHistorySelect;
cell0.appendChild(btn);
}


function btnHistorySelect() {
}

The event handler is being triggered, but there is no way to determine which specific button initiated the click event.

Answer №1

To retrieve the id of the button that triggered the event, you can utilize either this.id or event.target.id.

function btnHistorySelect(event) {

    var id = this.id;

         or
   // var elem = event.target;
   // var id = elem.id

}

When you assign a function reference, the context of this within the function pertains to the current element in question.

Answer №2

function buttonSelection(event) {
   alert(event.target); // Displays the element that was clicked.
}

Answer №3

No id is required when using this feature

Answer №4

Within the btnHistorySelect function, the HTML input button element can be accessed using the this variable.

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

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Typescript: The type 'X' does not correspond with the signature '(prevState: undefined): undefined' in any way

My React Native app, which is written in TypeScript, has been giving me a hard time with an error lately. The issue revolves around a Searchable List feature. This list starts off with an Array of values and gets updated when users type into a search bar. ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Directive Template with Dynamic Fields (AngularJS)

I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field. Cu ...

My eCommerce website is currently experiencing some technical difficulties that need to be addressed

I'm in need of assistance with a particular error I encountered. I was following an ecommerce example application and everything seemed to be going smoothly until I clicked on "Shop Now." At that point, I received the following message: Server Error T ...

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

Unable to execute findOneAndUpdate as a function

I've been researching all morning and testing different solutions, but I'm still unable to resolve this issue. Every time I run the code below, I receive the error "TypeError: req.user.findOneAndUpdate is not a function": req.user.findOneAndUpd ...

Best practice for dynamically adding/storing/creating HTML elements on the fly

What is the best approach to dynamically add and store HTML controls for dynamically added elements on an HTML page? Currently, I am developing a widget-based system where users can choose which widgets they want to display. They have the flexibility to s ...

Tips on how to toggle the class of one specific element without affecting others

Whenever I click on a div, it expands. However, if I click on a collapsed one, both collapse and the first one returns to an inactive state. At this point, the last two are in both active and inactive states. And if at this time I click on the first one, t ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

Position the division at the location of the cursor for particular usemap components

Looking for a way to position a division on top of an image using a usemap. Interested in having the div only appear when the mouse hovers over a particular area, and at the precise location of the cursor. Came across some examples using jQuery, similar ...

"Implement a feature that allows users to click on an image in a queue using

These are the images I have: <img src=img1.jpg class=pic /> <img src=img2.jpg class=pic /> <img src=img3.jpg class=pic /> <img src=img4.jpg class=pic /> <img src=img5.jpg class=pic /> <img src=img6.jpg class=pic /> .Sh ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

How to effectively share an object array between controllers when utilizing modal windows in AngularJS

I'm currently working with an array of objects that I need to share between two controllers, one of which involves a modal window. Check out the JavaScript code below: angular.module('MyApp', ['ngMaterial', 'ngMessages' ...

Using browser's local storage: deleting an entry

I recently came across a straightforward to-do list. Although the inputs are properly stored in local storage, I encountered issues with the "removing item" functionality in JS. Even after removing items from the HTML, they still persist in local storage u ...

Steps to set up datetimepicker with varying date ranges for several input fields

I am having trouble getting a new date range for each text box in my form. It seems to only return the date range from the last textbox, even though I have made the textbox IDs dynamic. I have both start and end dates for each textbox and I have calculated ...