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

Successful PHP submission confirmation

I have implemented a basic PHP script on my website to handle email sending. <?php $headers ="From:<$from>\n"; $headers.="MIME-Version: 1.0\n"; $headers.="Content-type: text/html; charset=iso 8859-1"; mail($to,$su ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

Utilizing PHP for XML exportation and fetching it through AJAX to integrate it into the DOM, unfortunately, the XML content remains invisible

I've encountered a strange issue with a PHP script that generates valid XML output. I'm trying to fetch this data using an Ajax XMLHttpRequest call in the browser. Although Firebug confirms that the Ajax request is successful and the XML is vali ...

Errors are not being shown on mandatory fields in the form

After watching a tutorial video, I attempted to create a sign-up form. However, despite following all the steps, I encountered an issue where the Surname and Given name fields, which I set as required fields, were still processing blank when the form was s ...

Choose the immediate sibling located right after a specific element

My goal is to have the second paragraph following a h1 element display a dropcap, with the first being reserved for the author and date. Although I've tried using different CSS combinations like h1 + p::first-letter {}, it only affects the first para ...

Tips for properly styling the input type range element

Is there a way to fix the issue with my input type="range" styling using linear-gradient when the variable is set to 75%? It seems to be behaving incorrectly. body{ background: green; } .wrapper { width: 20vmin; } input { widt ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

JavaScript string manipulation function

Hey everyone, I need help finding a one-line solution in JavaScript to determine if a string contains a semicolon without using a loop. If anyone knows how to do this, please share your knowledge! ...

Implementing a method to pass total value to the <td> tag in angular JS using controller

I am having trouble calculating the total IR for each table cell. Despite my efforts, the function is not working as expected and I can't figure out why. $scope.getTotalb = function () { var totalb = 0; for (var i = 0; i < $scope ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Having trouble accessing the information stored in the Firebase Database?

As a newcomer to Firebase and JS, I am attempting to showcase user information on a webpage that is stored within the Firebase database. The data format resembles the image linked here I have written this Javascript code based on various tutorials. Howev ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

Wordpress Sub-Menu Being Eclipsed by Banner

After upgrading my Wordpress to version 3.5.1, I noticed a problem on my site where the Submenus are loading but quickly getting hidden behind the Banner. Despite trying various modifications in the CSS file, the issue remains unresolved (and might have wo ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

Error: Unable to iterate over the elements of `this.state` as it is

NEW UPDATE I encountered an issue with the response being an array, but it was actually coming from the backend (Express/Build folder) Revisiting an old issue that I faced some time ago. In my development environment, everything works fine. But once I d ...

Tips for indicating errors in fields that have not been "interacted with" when submitting

My Angular login uses a reactive form: public form = this.fb.group({ email: ['', [Validators.required, Validators.email]], name: ['', [Validators.required]], }); Upon clicking submit, the following actions are performed: ...

Angular 8 UI not displaying mockAPI data as expected

My mockAPI is successfully fetching the data, but the json response structure is quite complex. It looks something like this: [ { "planList": [ // plan details here ] } ] Everything in the UI is displaying correctly, except ...