Unable to retrieve the value of a selected table cell from dynamically generated HTML tables

I've gone through a plethora of Google and Stack Overflow examples

To showcase my problem, I have set up a fiddle.

Issue: "Upon clicking on a person's name, I want to retrieve their name from the first column." While I managed to create a click event using Jquery that highlights each row in yellow upon hover, the code I used outputs all text values for every row in that column.

 $(document).on('click', '.nameField', function () {
        var x = $(this).text();
        console.log(x);
    });

View the demonstration here

Additional Information:

Click on the button labeled "Fill DIV with Dynamic Table"

At the top, you'll find a STATIC one that is able to retrieve the name without any issues, however, there is only one row present

UPDATE: I also need the alias available on that row. I have created a new class on the td in the alias column. How can I access it?

Access the updated fiddle here

Answer №1

If you want to experiment with it:

let element = $(this).text();

To retrieve the nickname, use:

let alias = $(this).siblings('.alias').text();

Answer №2

$(".nameField") retrieves a nodelist of elements. It is advisable to use this. Check out this Fiddle link

$('.person').on('click', function() {
  var x = $(".person").text();
  console.log(x);
});


$(document).on('click', '.nameField', function() {
  var x = $(this).text();
  console.log(x);
});
$('#fillTable').click(function() {

  var data = [{...}];
    
// Function to generate table dynamically
function writeRegister(allData) {
  var strResult = "<table id='headerTable' class='table'><thead id='headers'><th>Name</th><th>Office</th><th>Title</th><th>Department</th><th>Alias</th>";

  $.each(allData, function(index, issues) {
    strResult += "<tr><td class='nameField'> <a href='#'>" + issues.LAST_NAME + " " + issues.FIRST_NAME + " " + issues.INITIALS + "</a></td><td>" + issues.OFFICE + "</td><td>" + issues.TITLE + "</td>";
    strResult += "<td>" + issues.DEPARTMENT + "</td><td>" + issues.ALIAS_NAME + "</td>";
    strResult += "</tr>";
  });
  strResult += "</table>";

  $("#divEmpResult").html(strResult);
}
td.person {
  color: red;
}
.person:hover {
  color: red !important;
  background-color: yellow;
}
.nameField:hover {
  color: red !important;
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="person"><a href='#'>Miller Bob T</a>

    </td>
  </tr>
</table>
<!-- Dynamic table generation -->
<input type="button" id="fillTable" value="Fill DIV with Dynamic Table">
<div id="divEmpResult" style="margin-left: 15px"></div>

Answer №3

Instead of using $(".nameField") to select all td elements with the class "nameField", consider utilizing the keyword "this".

$(document).on('click', '.nameField', function () {
    //console.log('t');
    var x = $(this).text();

    //var x = $(this).parent(".nameField").text();
    console.log(x);

});

Answer №4

Here's a useful alternative: first select the tr element, then locate the .nameField associated with it

$(document).on('click', 'tr', function () {
    //console.log('t');
    var that = $(this);
    var x = that.find($(".nameField")).text();

    //var x = $(this).parent(".nameField").text();
    console.log(x);

});

Answer №5

Many jQuery functions fail to identify elements that are generated dynamically.

To solve this issue, you can utilize the .live() function.

$(document).live('click', '.nameField', function () {
        //console.log('t');
        var x = $(".nameField").text();

        //var x = $(this).parent(".nameField").text();
        console.log(x);

    });

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

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

Modify the scrollbar's width, color, and corner radius to customize its appearance

Here is the table code where the styles are applied. By setting the tablecontainer height to 600px, we can make the table scrollable. However, I would like to customize the scrollbar with a different color, width, and corner radius. <TableContainer s ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Node.js course utilizing MySQL library implementing Object-Oriented Programming concepts

Learning to work with MySQL in Node has been quite challenging for me. I am using the npm package 'mysql' for my project. I am aiming to follow OOP principles by creating an independent class to handle all my DB requests. However, I am facing an ...

SQL code to search for data matching certain criteria using the LIKE operator and restricting the results with

After completing my project in Yii, I am now looking to display values related to the items I am showcasing. I am interested in showing related recipes based on the cuisine and course fields from the recipe table. Below is the condition I have in mind. Ho ...

Tips for modifying the color of highlighted text?

Can you help me change the color of this text from blue to dark green by using Javascript or HTML/CSS? Please left-click and drag over the text to select it. ...

Struggling to close the dropdown with jquery

Check out this code snippet: https://jsfiddle.net/rajat_bansal/rtapaew5/1/ The jQuery section below is causing some trouble: $(document).ready(function(e) { $(".sub-handle").click(function() { if(!$(this).hasClass('showing-sub&ap ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

What causes programming languages to exhibit such behavior in the absence of any established hierarchy?

I was puzzled to discover that in Python and Javascript, when using this type of conditional statement, the logic seems off. If we add console.log statements in each condition, it appears that the comparison should be false != true, meaning that the code s ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

Steps to sending a parameter to an AngularJS $http success callback

In my AngularJS application, I have implemented the following code: $http.get('/plugin/' + key + '/js').success(function (data) { if (data.length > 0) { console.log(data); // Here, I also need to retrieve the val ...

Is it feasible to display a message for a certain duration without using the alert() function upon clicking a button?

I'm working on a NEXT.JS project and I need to display a <p> element under my button for a specific duration before it disappears. I don't want to use the alert() function. Any suggestions on how to achieve this? ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Is it time to release the BufferGeometry?

My scene objects are structured around a single root Object3D, with data loaded as a tree of Object3Ds branching from this root. Meshes are attached to the leaf Object3Ds using BufferGeometry/MeshPhongMaterial. To clear the existing tree structure, I use t ...

What is the best way to confirm if a Json response is empty or not?

{"PatientPastMedicalHistoryGetResult":{"PastMedicalHistory":[]}} The PastMedicalHistory object does not contain any values. How can I verify if it is empty? ...

What steps can be taken to designate a personalized element for showcasing autocomplete options?

I want to change the way the suggested autocompletions are displayed by placing them in a separate div instead of showing them as a pop-up menu over the autocomplete widget. This decision was made because we are using autocomplete to alert users about pote ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

Import Image Data into AngularJS

I've got a dilemma with downloading images from a browser into a zip file using JSZip. I have a list of image URLs from the server, and I'm trying to use the jszip library to create a zip file. Here's what I attempted: var img = zip.folder( ...