I constructed a table using a loop, and now I am interested in setting up a click event for each individual cell

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        string empCode = ds.Tables[0].Rows[i]["EMP_CODE"].ToString();
        string empName = ds.Tables[0].Rows[i]["EMP_NAME"].ToString();
        string gradeCode = ds.Tables[0].Rows[i]["GRADE_CODE"].ToString();

        tr = new TableRow();

        td = new TableCell();
        td.Text = empCode;
        tr.Cells.Add(td);
        tableButton.BackColor = System.Drawing.Color.Transparent;
        tableButton.Text = empCode;

        td = new TableCell();
        td.Text = empName;
        tr.Cells.Add(td);

        td = new TableCell();
        td.Text = gradeCode;
        tr.Cells.Add(td);

        table1.Rows.Add(tr);

    }

This is the code I am working on.

As I create each cell in the table, I want to add a click event to the cell. What steps should I take to achieve this? Please advise.

Answer №1

If you want to generate dynamic HTML content and insert it into the InnerHtml property of a server-side control, you can follow this example:

<form id="form1" runat="server">
    <div>
        <table id="table1" runat="server">
        </table>
    </div>
</form>

string html = "";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    string empCode = ds.Tables[0].Rows[i]["EMP_CODE"].ToString();
    string empName = ds.Tables[0].Rows[i]["EMP_NAME"].ToString();
    string gradeCode = ds.Tables[0].Rows[i]["GRADE_CODE"].ToString();

    html += "<tr>";
    html += "    <td onClick='MyOnclickEvent()'>" + empCode + "</td>";
    html += "    <td onClick='MyOnclickEvent()'>" + empName + "</td>";
    html += "    <td onClick='MyOnclickEvent()'>" + gradeCode + "</td>";
    html += "</tr>";
}
table1.InnerHtml = html;

Answer №2

To handle dynamically created content, you can bind a single event listener to the table and adjust the event capturing mechanism to access the cell content.

const table = document.querySelector('table')

table.addEventListener('click', event => {
  if(event.target.tagName === "TD") {
    console.log(event.target.innerText)
  }
}, {capture: true})
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html>

Answer №3

There are a couple of ways to achieve this.

  1. One way is to add a click event listener to each cell in your table and handle it accordingly.
  2. Another approach is to iterate through your table rows and columns, assigning a click listener to each cell.
   for (var i = 0; i < table1.rows.length; i++) {
          for (var j = 0; j < table1.rows[i].cells.length; j++)
              table1.rows[i].cells[j].onclick = function () {
              alertCellContent(this);
           };
        }
      }
    
 function alertCellContent(cell) {
   alert(cell.innerHTML);
 }

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

AutoCAD Command Denied: Attempting to use the 'Undo' command from LISP was unsuccessful

For the last 3 weeks, I've been attempting to programmatically call undo commands without success. In my most recent effort, I have tried invoking LISP code from C#. The current structure of my C# Method is as follows: [CommandMethod("TestLispFromC#" ...

Preventing the dropdown options from appearing in Angular when clearing the input field

In a reusable component, I implemented some simple logic to clear the value of a select input when the 'x' button is clicked. select.component.ts @Input() selectFormControlName: string; @Input() selectAbstractControl: AbstractControl; ... ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

Implementing CSS styles on selected elements using jQuery

My current HTML layout looks like this.. <div class="container> <div class="panel"> <div> <div> <div> <img class="match" src="myimage.jpg"> &l ...

Arranging icons at the bottom of the post with a text box that changes dynamically

My challenge is that when the content in a box overflows, the box size increases and pushes the icons out of place. I want to ensure that the icons remain in a fixed position. This is how it currently looks: The comment, delete, and likes count end up on ...

JavaScript error leading to ERR_ABORTED message showing up in the console

When I try to load my HTML page, my JavaScript code keeps throwing an error in the console. I am attempting to import some JavaScript code into VSCode using an app module for future reuse. The code is being run through a local server. Error Message: GET ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Using jQuery's append function, you can dynamically generate a dropdown list in PHP code

One of the challenges I'm facing is related to a button that, when clicked by a user, should append a dropdown list to the HTML. I am using PHP to retrieve data from a database and fill the dropdown list with it. However, upon trying out this code, it ...

Is the absence of http(s) in <link ...> causing any issues?

I recently noticed a peculiar link on the Font Awesome homepage that seems to work without including http or https. <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> This made me wonder, what does // a ...

Utilizing Express.js: Passing the req Object to Middleware without the Need for a New Multer Route

Hello to the Express.js and StackOverflow communities! I hope this question is not a duplicate, as I searched and found nothing similar. Currently, I am working on a project using Multer with Express to enable users to upload images, which will be saved a ...

What could be causing my jQuery $(this).next().removeAttribute to not function properly?

I am currently working on a file upload form that includes buttons like "Choose file", "Upload", and "Add other file". I am facing an issue where the "disabled" attribute is successfully removed from the first Upload button upon File Input change, but it ...

Using NextJS: Customizing page names for cleaner URLs

Currently working on a project in NextJS, I've come across an interesting observation. The file name within my pages folder seems to directly correspond to the path displayed in the URL bar. My question is, can I possibly create a structure like this ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

The attempt to make an HTTP request to the Logic app results in an error message stating that "Property selection is not enabled for values of the type 'String'"

I have a simple logic app set up to perform a task, with an HTTP trigger that expects a JSON object. To call this logic app trigger from C#, I use the following code: var postData = new QERestartModel { AppName = appname, ...

Tips for updating multiple documents in a MongoDB database using an array of values

I have a range of Product items in my inventory and when a client places an Order, they submit an array of objects. Each object in the array includes the _id product (objectId) and the quantity they purchased. [ {producId: "dshsdsdh72382377923", quantity: ...

Struggling with extracting and transferring data from a span tag to another field within the same form using selenium and python

I am struggling with an issue while running a code using selenium in Python. I am trying to extract values from span tags and store them in variables named "cap1, cap2, and cap3." After saving these values, I need to input them into another field on a web ...

The error message "item is not defined in nodejs" indicates that the variable

I am facing an issue while trying to retrieve data from a JSON file using Node.js and Express. I have defined the methods with exports, but I keep getting errors in my browser. I am unsure why it is not functioning correctly, as I have specified the metho ...

Performing an Ajax request upon the completion of page loading

I am currently working on creating a search functionality for a page, where users can input text into a search box and the page will display results based on their search. However, I am facing some timing issues as the blank search page is loading before ...

Update Panel triggering postback with RadioButton control

My aim is to incorporate the following controls within an update panel to prevent the entire page from refreshing. I have noticed that when I click the button, the page remains static. However, the issue arises when I attempt to modify the radio button, ...

stacking order of floated and positioned elements

After researching on MDN and reading through this insightful blog post, it is suggested that in the absence of a z-index, positioned elements are supposed to stack above float elements when they overlap. However, upon closer examination, the example prov ...