Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery.

$('.tbody').on('click','tr td:nth-child(1)', function () {
    var id = $(this).closest("td").find('td:eq(1)').text();
    alert(id)
});

I have implemented an onclick function to extract the value of the second td based on the provided code. However, upon execution, I receive an empty alert. I am uncertain of what went wrong and require assistance. According to my understanding, $(this).closest("td").find('td:eq(1)').text() should locate the next td and the .text() method should display the content within that td. Is this correct?

The following snippet illustrates the issue described above

Your help will be greatly appreciated!

Thank you in advance!

$(function () {
    $('.tbody').on('click','tr td:nth-child(1)', function () {
        var id = $(this).closest("td").find('td:eq(1)').text();
        alert(id)
    });
});
#items {
    border-collapse: collapse;
    width: 100%;
}
#items th {
    background-color: #009999;
    color: white;
    border : 1px solid;  
}
#items td{
    border : 1px solid;
}
#items tbody{
    height:200px;
    overflow-y:auto;
}
#items thead,.tbody{
    display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">    
    <table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; "  id="items">
<thead>
            <tr>
        <th style="width:100px;">Fee Type</th>
<th style="width:100px;">Charges per Qty</th>
<th style="width:100px;">Qty</th>
    </tr>
</thead>
<tbody class="tbody">
<tr>
            <td style="width:100px;">a</td>
            <td style="width:100px;">b</td>
            <td style="width:100px;">c</td>
        </tr>
        <tr>
            <td style="width:100px;">d</td>
            <td style="width:100px;">e</td>
            <td style="width:100px;">f</td>
        </tr>
</tbody>
    </table>
</div>

Answer №1

Your approach is flawed because the reference to this points to the existing td, making closest('td') ineffective. Additionally, using find() won't work as it's not the parent of the desired td. The correct method is to utilize closest('tr') instead:

var id = $(this).closest("tr").find('td:eq(1)').text()

Alternatively, a simpler way to achieve this is by employing next() since the td elements are siblings:

$(function() {
  $('.tbody').on('click', 'tr td:nth-child(1)', function() {
    var id = $(this).next().text();
    console.log(id);
  });
});
#items {
  border-collapse: collapse;
  width: 100%;
}

#items th {
  background-color: #009999;
  color: white;
  border: 1px solid;
}

#items td {
  border: 1px solid;
}

#items tbody {
  height: 200px;
  overflow-y: auto;
}

#items thead,
.tbody {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; " id="items">
    <thead>
      <tr>
        <th style="width:100px;">Fee Type</th>
        <th style="width:100px;">Charges per Qty</th>
        <th style="width:100px;">Qty</th>
      </tr>
    </thead>
    <tbody class="tbody">
      <tr>
        <td style="width:100px;">a</td>
        <td style="width:100px;">b</td>
        <td style="width:100px;">c</td>
      </tr>
      <tr>
        <td style="width:100px;">d</td>
        <td style="width:100px;">e</td>
        <td style="width:100px;">f</td>
      </tr>
    </tbody>
  </table>
</div>

Answer №2

To achieve the desired outcome, simply update the nearest element from 'td' to 'tr'

var id = $(this).closest("tr").find('td:eq(0)').text();

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

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

Displaying the "Ad Blocker Detected" image next to the advertisement

I am attempting to create a feature where if adblock is enabled, an image will display behind the ad banner on my website with the message "Please consider disabling adblock". Unfortunately, it is only showing up as a bordered box. Here is how the box ap ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

What are some effective strategies for optimizing the organization of express middlewares?

Currently, I have successfully implemented the following code using node and express. The code is located in file app.js app.use(function (req, res, next) { fs.mkdir('uploads/', function (e) { if (!!e && e.code !== 'EEX ...

Trouble triggering hidden radio button in Angular 9 when clicked

I have implemented radio buttons within a div with the following CSS styles (to enable selection by clicking on the div): .plans-list { display: flex; justify-content: center; margin: 2rem 0; .plan { display: flex; margin: 0 0.5rem; p ...

Conflicts arising between smoothState.js and other plugins

After successfully implementing the smoothState.js plugin on my website, I encountered an issue with another simple jQuery plugin. The plugin begins with: $(document).ready() Unfortunately, this plugin does not work unless I refresh the page. I have gone ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Tips on utilizing HTML tags in shiny context to highlight or potentially enlarge the font size for sprintf使

Can anyone help me figure out how to bold or increase the font size for my sprintf in R? I attempted the code below but it didn't work as expected. Instead of bolding the text, the "

Continuously receiving the value of undefined

I am currently working on a JavaScript Backbone project and I have declared a global object as follows: window.App = { Vent: _.extend({}, Backbone.Events) } In the initialize function, I have done the following: initialize: function () { window.App ...

Choose the initial drop-down option and concentrate on it

How can I target the first drop down node (select element)? I have tried using this code to focus on the first input, but I am looking for a way to target the first select (drop down). $('.modal :input:first').focus(); Unfortunately, this meth ...

utilizing a dynamic value within CSS modules for class naming

Struggling to incorporate a variable into a CSS module class name in Next.js. Finding it challenging to determine the correct syntax. The variable is fetched from the API: const type = red Here's how I'm attempting to achieve it: <div clas ...

Developing pagination functionality in ReactJS

I came across this piece of code in a forum (how to implement Pagination in reactJs): constructor() { super(); this.state = { todos: ['a','b','c','d','e','f','g','h ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Angular form displayed on the screen

I'm having trouble finding a solution to this issue, as the form data is not being output. var app = angular.module('myApp', []); app.controller('mainController', ['$scope', function($scope) { $scope.update = funct ...

Adjust the HTML5 input type range to snap to the midpoint with precision by increasing the number of steps

Currently, I have an <input type=range> element with a substantial number of steps allowed (around 60,000). Certain steps, such as the midpoint, hold greater significance for me and I would like a caret or snap functionality when the user approaches ...

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

A slender gap of white space delicately separates the transformed parent from its offspring

When trying to align a parent div with a child div that has the same background-color as the parent's border-color, I am encountering an issue. Despite my efforts, there seems to be a thin line of whitespace separating the two divs. It is worth notin ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...