Obtain the contents of the table row td element within the specified div class without relying on

I am currently working with a basic table layout, shown below:

<table>
    <tbody>
        <tr>
           <td>img</td>
           <td class="mediaTitle"><span class="media_title">Media Name Title</span></td>
           <td>type</td>
           <td>2017-08-30 10:30am</td>
           <td>2017-09-01 11:34am</td>
           <td>Smith, Tater</td>
           <td><i class="fa fa-arrow-circle-down action" data-action="download_media" title="Download Media" aria-hidden="true"></i></td>
           <td><i class="fa fa-refresh action" data-action="restore_media" title="Restore Media" aria-hidden="true"></i></td>
           <td><i class="fa fa-trash-o action" data-action="delete_media" title="Permanently Delete Media" aria-hidden="true"></i></td>
        </tr>
   </tbody>
</table>

This table is intended to display numerous rows of dynamic data. I have created a JavaScript method linked to a data-action attribute named delete_media. The goal is to retrieve the text value within the td tr.mediaTitle of the current row when clicking on a link with the class .fa-trash-o.

In my initial attempt using $(this), where I assume it refers to the clicked button and traverse up the DOM tree to find the relevant element, I encountered issues:

Blah.prototype._delete_media = function(data,e,el) {
        var self = this,
            mediaTitle = $(this).closest('tr').find('td.mediaTitle').text();

        console.log(mediaTitle);
});

Unfortunately, this returned an undefined or empty value. It seemed that something was missing in my approach.

Subsequently, by wrapping the functionality in an .onClick event handler, I was able to obtain the desired text value:

Blah.prototype._delete_media = function(data,e,el) {
        var self = this;

        $('.fa-trash-o').click(function() {
            var mediaTitle = $(this).closest('tr').find('td.mediaTitle').text();

        console.log(mediaTitle);
        });
});

The utilization of a separate click function within the existing method connected to data-action felt confusing. I realize there might be a more efficient way to manipulate elements without adding additional handlers. Seeking assistance from those knowledgeable in jQuery to guide me towards resolving this dilemma. Any insights would be greatly appreciated.

Answer №1

UPDATE

Make the change from $(this) to $(e.target). I have also included an additional row in the demo and numbered the text for better differentiation.


To simplify, you can directly use the selector td.mediaTitle.

Demo

$('.fa-trash-o').on('click', function(e) {
  var mediaTitle = $(e.target).closest('tr').find('td.mediaTitle').text();

  console.log(mediaTitle);
});
<link href="https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css" rel="stylesheet>


<table>
  <tbody>
    <tr>
      <td>img</td>
      <td class="mediaTitle">
        <span class="media_title">Media Name Title 1
             </span>
      </td>
      <td>type</td>
      <td>2017-08-30 10:30am</td>
      <td>2017-09-01 11:34am</td>
      <td>Smith, Tater</td>
      <td>
        <i class="fa fa-arrow-circle-down"></i>
      </td>
      <td>
        <i class="fa fa-refresh"></i>
      </td>
      <td>
        <i class="fa fa-trash-o"></i>
      </td>
    </tr>

    <tr>
      <td>img</td>
      <td class="mediaTitle">
        <span class="media_title">Media Name Title 2
             </span>
      </td>
      <td>type</td>
      <td>2017-08-30 10:30am</td>
      <td>2017-09-01 11:34am</td>
      <td>Smith, Tater</td>
      <td>
        <i class="fa fa-arrow-circle-down"></i>
      </td>
      <td>
        <i class="fa fa-refresh"></i>
      </td>
      <td>
        <i class="fa fa-trash-o"></i>
      </td>
    </tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

If you're looking to simplify this process, consider creating a plugin that wraps all the functionality. The click event is delegated to the table itself to accommodate future dynamically added rows.

Each action defined by [data-action] has its own corresponding actionMethod. Each row contains data attributes specific to each media item.

To use the plugin, simply call: $('#my-table').mediaActions()

Given that multiple instances are unlikely to be used simultaneously, there isn't a significant advantage to implementing prototype inheritance. All named functions will remain isolated within the IIFE that encloses the plugin.

(function($) {
  // hoisted references to functions at bottom
  var actionMethods = {
    'restore_media' : restore_media,
    'delete_media'  : delete_media,
    'download_media': download_media
  };

  $.fn.mediaActions = function(opts) {
    // return this to allow jQuery chaining
    return this.each(function() {
      // delegate clcik listener to the table with `[data-action]` targets
      $(this).on('click', '[data-action]', function(e) {
        var $el = $(this),
          $row = $el.closest('tr'),
          action = $el.data('action'),
          media_data = $row.data();
        // call method for this action passing in current row and row data
        // TODO : make sure method exists for current action
        actionMethods[action]($row, media_data);
      });
    })
  }

  function restore_media($row, media_data) {
    // somehow validate it needs restoring first
    console.log('Restoring', media_data);
    $row.removeClass('deleted');
  }

  function delete_media($row, media_data) {
    console.log('Deleting', media_data);
    $row.addClass('deleted');
  }

  function download_media($row, media_data) {
    console.log('Downloading', media_data);
  }

})(jQuery);
$('#my-table').mediaActions()
tr.deleted {
  background: #ccc
}
<link href="https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<table id="my-table">
  <tbody>
    <tr data-media_title="Media Name Title" data-media_id="1234">
      <td>img</td>
      <td class="mediaTitle"><span class="media_title">Media Name Title</span></td>
      <td>type</td>
      <td>2017-08-30 10:30am</td>
      <td>2017-09-01 11:34am</td>
      <td>Smith, Tater</td>
      <td><i class="fa fa-arrow-circle-down action" data-action="download_media" title="Download Media" aria-hidden="true"></i></td>
      <td><i class="fa fa-refresh action" data-action="restore_media" title="Restore Media" aria-hidden="true"></i></td>
      <td><i class="fa fa-trash-o action" data-action="delete_media" title="Permanently Delete Media" aria-hidden="true"></i></td>
    </tr>
    <tr data-media_title="Media  2" data-media_id="678">
      <td>img</td>
      <td class="mediaTitle"><span class="media_title">Media  2</span></td>
      <td>type</td>
      <td>2017-08-30 10:30am</td>
      <td>2017-09-01 11:34am</td>
      <td>Foo, Bar</td>
      <td><i class="fa fa-arrow-circle-down action" data-action="download_media" title="Download Media" aria-hidden="true"></i></td>
      <td><i class="fa fa-refresh action" data-action="restore_media" title="Restore Media" aria-hidden="true"></i></td>
      <td><i class="fa fa-trash-o action" data-action="delete_media" title="Permanently Delete Media" aria-hidden="true"></i></td>
    </tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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 query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Refreshing Firebase tokens

Currently, I am utilizing Firebase for authentication within my React application. Additionally, I have an Express server that provides a REST API. This API includes a middleware function that utilizes firebase-admin to verify the idToken sent from my app ...

Utilizing PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

Behold the magic of a three-column layout with sticky scroll behavior and an absolute

I am struggling with a layout that involves 3 columns, each with its own independent scroll. The first column contains an absolute element that should overflow on the x-axis, but I am having trouble getting the overflow-x:visible property to work when comb ...

Is there a way to make Express.js pass parameters with special characters exactly as they are?

I am currently working on a project within the freeCodeCamp "API and Microservices" curriculum that involves using Express.js to handle routes. The project itself is relatively straightforward, with some pre-defined routes and others that need to be creat ...

The issue with the $(window).width() property not functioning correctly in Internet Explorer

Currently, I have a Div element with absolute positioning: <div id="target" style="height: 300px; position: absolute; top: 275px;"></div> My goal is to calculate the horizontal resolution of the screen using JavaScript. With this width, I the ...

Modify the position of the CSS background for the Y-axis using jQuery

Let's consider a scenario with the following table: <table> <tr> <td class="t"></td> <td class="e"></td> <td class="s"></td> <td class="t"></td> </ ...

Issue with jQuery Validation's require_from_group not functioning for specified class

I am struggling to properly implement require_from_group in this example form by applying it to the class instead of the name attribute. Any advice on what I might be overlooking? <h1>Form Validation Example</h1> <form id='registerForm ...

Having an issue with Local Storage returning undefined

I've been working on a form to input values and show the data on a different page after submission. Below is my form: <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" hr ...

Overlaying Divs and UI Blocking

I am currently working on an ASP.net project where I have a web page that contains both design time controls and run time generated controls. The dynamically generated content, such as a table, is appended to a div on the page known as a container div, wit ...

Error: The data entered is invalid because the delimiter ":" [0x3a] is missing in nodejs

I seem to be encountering an issue: Error: The data is invalid and there seems to be a missing delimiter ":" [0x3a] at Function.decode.find (/Users/Seleena/Documents/torrent/node_modules/bencode/lib/decode.js:114:9) at Function.decode.buffer ...

Verifying the presence of a popover

Utilizing bootstrap popover in my project, I am encountering an issue where the target variable may not always exist on the page. Currently, I am displaying the popover using the following code snippet - target = $('#' + currentPopoverId.data(& ...

How can I use JavaScript to access my templates directory in Django 3?

Perhaps I am taking the wrong approach here. My goal is to dynamically replace the content within the <nav> element using jQuery.load() when a specific <div> is clicked by the user. However, I am encountering difficulty in accessing the HTML fi ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

It appears that the $http request is causing an endless $digest Loop

Looking to determine a user's status in my AngularJS app in order to display specific functionality content, here is the HTML code in my view: <span ng-show="authService.isSuperUser()">You are a Super User</span> To check if the user has ...

Error: protractor encountered an unexpected issue

Currently, I am following this tutorial I went through all the steps mentioned in the tutorial except for what was suggested in this post instead of npm install -g protractor I opted for npm install -g protractor --no-optional So far, I have succe ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at https://i.sstatic.net/bDU7X.png The benefit of rendering JSON in string format within the page response is that it allow ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

Tips for organizing wells within bootstrap into separate columns

Looking for a way to organize my well list into two separate columns. I've included a link to my Plunker project here: https://plnkr.co/edit/35oC9Eochk6EPgKeI9he?p=preview. Below is the view section: <div class="well well-lg" ng-repeat="(key, d ...

Content is positioned to the left in a horizontal layout without a set width

I am currently assisting a friend with the development of her website. While I consider myself somewhat of an amateur in web design, I usually manage to overcome challenges by dedicating hours to searching for solutions online. However, this time I have no ...