Start with the parent element in jQuery code, instead of starting with the child element

In this scenario, a HTML table is provided with three buttons in the last column of each row. If the view button is clicked, it should retrieve the consumer ID for that specific row. The jQuery code to achieve this can be found here: http://jsfiddle.net/Lijo/nUbB2/

1) Are there any alternative jQuery solutions available?

2) Currently, the approach involves finding the button first, followed by its parent row and then extracting the Consumer ID column. Is it possible to streamline this process by starting from the row itself and locating the button and Consumer ID column sequentially?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>

 </title>

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script>
<script type="text/javascript">

    $(document).ready(function () {

        $('.resultGridTable tr > td > .actionButtonView').click(function () {
            //Traversing to obtain the parent row and necessary columns within the row
            var consumerID = $(this).parents('tr:first').find('td:first').text();
            var consumerName = $(this).parents('tr:first').find('td:nth-child(2)').text();
            var configID = $(this).parents('tr:first').find('td:nth-child(5)').text();

            alert(consumerID + "," + consumerName + "," + configID);

            //window.location.href("SubscribedAssociates.aspx?ConsumerID=" + consumerID + "&consumerName=" + consumerName + "&configID=" + configID);
            return false;

        });

    });
</script>
</head>


<body>
<table class="resultGridTable" cellspacing="0" id="detailContentPlaceholder_grdConsumers"
    style="border-collapse: collapse;">
    <thead>
        <tr>
            <th scope="col">
                <a>Consumer ID</a>
            </th>
            <th scope="col">
                <a>Consumer Name</a>
            </th>
            <th scope="col">
                <a>Consumer URL</a>
            </th>
            <th scope="col">
                <a>Status</a>
            </th>
            <th scope="col">
                <a>Config ID</a>
            </th>
            <th scope="col">
                Action
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <a href="SubscribedAssociates.aspx?ConsumerID=101">101</a>
            </td>
            <td>
                Consumer1
            </td>
            <td>
                http://Consumer1.compnay.com/wps/payroll
            </td>
            <td>
                Active
            </td>
            <td>
                101
            </td>
            <td>
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl02$btnView"
                    value="VIEW" id="detailContentPlaceholder_grdConsumers_btnView_0" class="actionButtonView"
                    style="color: White; background-color: Orange; font-weight: bold; width: 35px" />
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl02$btnEdit"
                    value="EDIT" id="detailContentPlaceholder_grdConsumers_btnEdit_0" class="actionButtonEdit"
                    style="color: White; background-color: Orange; font-weight: bold; width: 35px" />
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl02$btnDelete"
                    value="DELETE" id="detailContentPlaceholder_grdConsumers_btnDelete_0" class="actionButtonDelete"
                    style="color: White; background-color: Orange; font-weight: bold; width: 45px" />
            </td>
        </tr>
        <tr style="background-color: #E5E5E5;">
            <td>
                <a href="SubscribedAssociates.aspx?ConsumerID=102">102</a>
            </td>
            <td>
                Consumer2
            </td>
            <td>
                http://Consumer2.compnay.com/prd/sap/operations
            </td>
            <td>
                Active
            </td>
            <td>
                102
            </td>
            <td>
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl03$btnView"
                    value="VIEW" id="detailContentPlaceholder_grdConsumers_btnView_1" class="actionButtonView"
                    style="color: White; background-color: Orange; font-weight: bold; width: 35px" />
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl03$btnEdit"
                    value="EDIT" id="detailContentPlaceholder_grdConsumers_btnEdit_1" class="actionButtonEdit"
                    style="color: White; background-color: Orange; font-weight: bold; width: 35px" />
                <input type="submit" name="ctl00$detailContentPlaceholder$grdConsumers$ctl03$btnDelete"
                    value="DELETE" id="detailContentPlaceholder_grdConsumers_btnDelete_1" class="actionButtonDelete"
                    style="color: White; background-color: Orange; font-weight: bold; width: 45px" />
            </td>
        </tr>
    </tbody>
</table>
</body>
</html>

Answer №1

In order to optimize the process, consider implementing traversal with caching when accessing data from rows...

let currentRow = $(this).closest('tr')[0],
    userID = $(currentRow.cells[0]).text(),
    userName = $(currentRow.cells[1]).text(),
    configNumber = $(currentRow.cells[4]).text();

Furthermore, I utilized the DOM element directly for retrieving the child row.

Answer №2

Modify the HTML code to include the customer ID as a data attribute within the button element, like this:

<button class="actionButtonView" data-customer="101">Add</button>

Then, accessing the customer ID with jQuery is as simple as:

var customerId = ('.actionButtonView').data('customer');

Check out the documentation on .data() here

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

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

Troubleshooting HTTP Issues in Angular 2

I am currently facing an issue with my Angular 2 project's Http functionality. I have defined it as a parameter in the constructor, but it keeps printing as undefined. Below is the snippet of code from my project: import 'rxjs/add/operator/toPro ...

Using a physical Android device to test and run a Meteor mobile application

I'm struggling to get my Meteor app to run on my Android device (LG G2). Despite searching online for a solution, I haven't come across any similar issues. I followed the instructions carefully, added the Android platform to my project, and ran i ...

Creating functional links with card-img-overlay in Bootstrap v4

Encountering an issue where Bootstrap v4 cards utilizing card-img-overlay to overlay text on an image are causing links below the image to become unresponsive. The following links are functional: <div class="card" style="border-color: #333;"> & ...

Utilize CSS to prioritize the image and ensure it is responsive

I'm utilizing the 'featurette' feature in bootstrap. Currently, the page displays text on the left and an image on the right. As you reduce the browser size, they stack on top of each other, with the text appearing above the image. How can I ...

Utilizing border-radius specifically on the ul element to apply rounded corners to only the outer li items

I'm exploring a concept where I want to create a curved border around the list items, both on the outside and inside. Here are some examples: Right Check out the correct curved border here Wrong: See the incorrect curved border here Please note, ...

Try utilizing a single Associative Array instead of managing two separate index arrays when working in jQuery

Fiddle Example I've created a function that retrieves the next nearest number and its corresponding color based on a given value. For example, if the input is 500, the function will return 600 with the color beige. Currently, I'm using two separ ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Oops! Encounterred a TypeError stating "Unable to access properties of an undefined object" while working with react native

Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion variable, I encounter an error message: Cannot read properties of undefined (evaluating 'questObj[ ...

The width of a <div> element in CSS is not dependent on the width

Is there a way to make tables within a div have relative widths to each other? For example, if one table has a large image or long word causing it to extend to 100%, how can we ensure that the other tables in the same div also adjust to 100% width? CSS . ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

What is the process of defining a driver in Python in order to interact with a website

I have a task in my app that requires using Selenium to complete various functions. I am familiar with defining a driver and opening a webpage, but I need assistance regarding setting up the driver for an open net tab. Can anyone provide guidance on this ...

Difficulty encountered with PHP form insertion action

I am uncertain about where the errors might be occurring. I have attempted to inspect MySQL, but it seems that nothing is being inserted into my database. To begin with, here is a snippet of my HTML code: <form action="registerAction" method="POST"> ...

Integrate hash filtering for external links using a custom solution similar to Isotope

Illustration: When a user clicks on a specific link within a webpage, they will be redirected to tailored content in a designated section. I attempted to create a custom isotope using basic hide and show classes, but I am facing difficulty connecting ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...

I aim to align all the div elements to the right, except for the brand

I am working on customizing a navigation bar with links contained in a div tag. I would like to shift all the items to the right except for the navbar brand. My goal is to achieve a design similar to a PSD file, but I am encountering some issues with my co ...

After refreshing the compiler, the .toggleClass() method in React jQuery finally functions properly

I've been working on creating a sideboard for my react application and found this helpful example: https://codepen.io/illnino/pen/nwPBrQ. However, I've encountered an issue that I can't seem to solve on my own. What is the exact problem I&a ...

The method of AJAX Pattern for users to make interactive decisions

Currently, I am exploring different strategies to create interactive user decisions. My project involves a rather extensive form that users need to fill out. Upon submission, an AJAX-Post-Request is transmitted to the server. While some fault checks can be ...

Can a Highchart display a basic line chart with multiple values plotted against the x-axis?

I am looking to create a Highchart, specifically a basic line chart, that can display multiple values against the x-axis. My goal is to generate a line chart that represents the values (y-axis) over dates (x-axis). The challenge arises when there are mult ...

Struggling to replicate the Quad from .obj file using only Face3

My latest project involved creating a tool to analyze the lengths and angles of faces on a 3D object. However, after updating to version r67 of Three.js, I encountered an issue where Face4 disappeared and I struggled to replicate my previous work. Specific ...