How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript?

<html>
    <head>
    <title>Table Creation</title>

    <script language="javascript" type="text/javascript">
    function createTable()
    {
        document.write("<table >");

        for (var x = 1; x < 10; x++) {
            document.write("<tr >");

            for(var y = 1; y < 10; y++) {
                document.write("<td><button onclick='alert(\\"" + x + "," + y + "\\")'>index</button></td>");
            }

            document.write("</tr>");
        }

        document.write("</table>");
    }
    </script>
    </head>

    <body>
        <button onclick="createTable()">Try it</button>
        <div >
        </div>
    </body>
    </html>

For example, clicking on a cell in row 1 would display an alert with the indexes ((1,1),(1,2),(1,3)...), while clicking on row 2 would show ((2,1),(2,2),(2,3))

Answer №1

Take a look at this:

<html>
<head>
<title>Creating a Table</title>

<script language="javascript" type="text/javascript">
function createTable() {
    document.write("<table >");
    for (var x=1; x <10; x++) {
        document.write("<tr >");
        for(var y=1; y<10; y++) {
            document.write("<td><button onclick='alertButton("+x+","+y+")'>index</button></td>");
        }
        document.write("</tr>");
    }
    document.write("</table>");
}

function alertButton(row, col){
    alert('('+row+','+col+')');
}
</script>
</head>
<body>
<button onclick="createTable()">Try it</button>
<div >
</div>
</body>
</html>

Answer №2

<html>
    <head>
    <title>Generate Table</title>

    <script language="javascript" type="text/javascript">
    function displayTable()
    {
    document.write("<table >");
    for (var i=1; i <10; i++) {
    document.write("<tr >");
    for(var j=1; j<10; j++) {

    document.write("<td><button>("+i+","+j+")</button></td>");

    }
    document.write("</tr>");
    }
    document.write("</table>");
    }
    </script>
    </head>
    <body>
    <button onclick="displayTable()">Click to Generate Table</button>
    <div >
    </div>

    </body>
    </html>
    </html>

Answer №3

Give this a shot:

Substitute the current line with:

document.write("<td><button onclick='getLocation(this)'>index</button></td>");

Additionally, include this new function:

function getLocation(elem){
  alert(elem.closest('tr').rowIndex + "," 
  + elem.closest('td').cellIndex);
}

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

Modify the button's background color for Django's image upload field

In one of the forms in my Django application, I have included a field that allows users to upload an image. Here is the code for this field: image = models.ImageField(upload_to=upload_location, null=True, blank=True) To display this field in my form tabl ...

Updating lists using PHP and Ajax: a dynamic approach

I am currently using a chat service that relies on polling every 20 seconds for new user data in the chat room. I am looking to improve this process by only downloading information for new users who have just joined, rather than re-downloading old data f ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

Executing Python script via AJAX or jQuery

I need to execute Python scripts from JavaScript. The goal is to provide an input String to the Python script as an argument and then showcase the output on our webpage. Below is the Python code that runs smoothly on my Linux box: ./sample.py 12345 produc ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Regularly fetching images from PHP page

Recently, I encountered a challenge with a PHP page that retrieves arguments from the URL to generate an image. The image type (png, gif, etc.) is unknown. Typically, the page is used to embed the image in a standard HTML page like so: <img src="page.p ...

What is the process for developing an Alphabetizer Program?

I have been working on this and I am having trouble getting the "alphabetized" version to display. I've tried a few things already, but I'm not sure what is missing or needs to be changed. Any advice on how to fix this would be greatly appreciate ...

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...

Revamping Slideshows: Bringing CSS Animation to JavaScript

/* JavaScript */ var slides=0; var array=new Array('background.jpg','banner.jpg','image.jpg'); var length=array.length-1; $(document).ready( function(){ setInterval(function(){ slides++; ...

overlaying an image with a CSS box and then dynamically removing it using JavaScript

I am new to JavaScript, so please bear with me if this question seems quite simple. I am facing an issue with my current task. There is an image on a web page. My goal is to place a black box on top of the image (using CSS) to cover it up. Then, with th ...

What is the best way to align a checkbox and text in the same row within a Mailchimp embedded form?

I am troubleshooting a styling issue with my Mailchimp form that has groups. The problem I'm encountering is that the checkboxes are displaying on one line while the text appears on the next line in an unordered list format. To see the issue for yours ...

Using values from a select menu in a math calculation without including a decimal point

I am working with a dropdown menu that contains various values... <select id="number1a" onChange="Addition()"> <option value="0" selected>-</option> <option value="10">10</option> <option value="7.5">7.5</optio ...

Why is the click event not working in IE8 for JavaScript / jQuery?

There seems to be an issue with the program not functioning properly in IE8 for some users. The website in question is an English course where certain individuals are experiencing difficulty clicking on the correct answers. To view a demonstration of this ...

The LoopBack framework encountered an issue where it could not execute the 'post' method due to being undefined

As a newcomer to loopback and node.js, I have successfully created two models - Rating and RatingsAggregate. Utilizing the loopback explorer, querying and posting against the API has been smooth. In an attempt to establish basic business logic, I am curre ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

What is the best way to resolve the CSS border styling issue surrounding the anchor element?

I created a simple sign-up form for my school project where users can choose their roles. I'm facing an issue with the border under the anchor tag and I need help fixing it. How can I ensure that the space at the top is equal to the bottom as well? T ...

Bidirectional data connection in a Meteor application

I've developed a form-based application and I would like to allow users to fill out the form partially and return to it at a later time if needed. I've utilized iron router to create a unique URL for each instance of the form, enabling users to a ...

Populate a select list in real time with dynamically generated options

I'm facing a challenge at the moment; I am using JavaScript to dynamically generate select boxes, however, I require Ajax to populate them with options. At the moment, my code is returning undefined and I am unsure of how to proceed. While my PHP succ ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...

Guide on creating a conditional column in a kendo UI grid with the use of AngularJS

Is there a way to dynamically add a column to the Kendo UI grid based on JSON data? Consider the following JSON input: [{ "ProductID": 1, "ProductName": "Chai", "Supplier": { "SupplierID": 1, "SupplierName": "Exotic Liquid ...