jQuery Datatables have trouble accessing specific row information when the table is set to be responsive

Currently, I'm utilizing the jQuery DataTables plugin along with the responsive addon to dynamically display and hide columns based on the size of the browser window.

One of the columns is labeled as Actions, which permits users to edit a record by clicking the pencil icon within that column. When the pencil icon is clicked, the script searches for the id associated with the element that was clicked.

This functionality only works when the table is not in responsive mode. When the table goes into responsive mode and additional columns are expanded:

https://i.stack.imgur.com/C3ayU.jpg

If the pencil icon is clicked in this scenario, the following error occurs:

Cannot read property 'id' of undefined

This issue arises because the plugin fails to locate the row belonging to the clicked element.

To demonstrate this problem, I have included a code snippet and a JSFIDDLE link.

Code snippet goes here
Additional scripts and links go here

Could someone point out any mistakes in my approach? Or is this a known bug?

Your suggestions for resolving this issue would be greatly appreciated.

Thank you for your help.

Answer №1

After discussing the comments, I have decided to post it here.

$(document).ready(function() {
  var table = $('#example').DataTable({
  "columns": [{
    data: 'name'
  },
  {
    data: 'position'
  },
  {
    data: 'office'
  },
  {
    data: 'age'
  },
  {
    data: 'salary'
  },
  {
    data: null,
    render: function(data, type, row) {
      return '<a href="javascript:void(0)" class="btn btn-link btn-warning btn-icon btn-sm "><i class="fas fa-pencil-alt edit" data-id="' + data.id + '" ></i></a>'; // Removed same class in i element from a element
    }
  }
],
responsive: true
});

var users = [{
  id: 1,
  name: "Penny",
  position: "waitress",
  office: "none",
  age: "25",
  salary: "1550$"
},
{
  id: 2,
  name: "Sheldon",
  position: "physical",
  office: "university",
  age: "39",
  salary: "8435$"
},
{
  id: 3,
  name: "Leonard",
  position: "physical",
  office: "university",
  age: "35",
  salary: "7842$"
},
];

$('#example').DataTable().clear().draw();
$('#example').DataTable().rows.add(users);
$('#example').DataTable().draw();

$(document).on('click', '.edit', function(element) {

console.log($(this).data('id')); // Directly retrieves the value on click
});
 });

Answer №2

Here is an alternative approach you can consider:

  $(document).ready(function() {
      var table = $('#example').DataTable({
        "columns": [{
            data: 'name'
          },
          {
            data: 'position'
          },
          {
            data: 'office'
          },
          {
            data: 'age'
          },
          {
            data: 'salary'
          },
          {
            data: null,
            render: function(data, type, row) {
              return '<a href="javascript:void(0)" data="' + data.id + '" class="btn btn-link btn-warning btn-icon btn-sm edit"><i class="fas fa-pencil-alt"></i></a>';
            }
          }
        ],
        responsive: true
      });

      var users = [{
          id: 1,
          name: "Penny",
          position: "waitress",
          office: "none",
          age: "25",
          salary: "1550$"
        },
        {
          id: 2,
          name: "Sheldon",
          position: "physical",
          office: "university",
          age: "39",
          salary: "8435$"
        },
        {
          id: 3,
          name: "Leonard",
          position: "physical",
          office: "university",
          age: "35",
          salary: "7842$"
        },
      ];

      $('#example').DataTable().clear().draw();
      $('#example').DataTable().rows.add(users);
      $('#example').DataTable().draw();

      $('#example').on('click', '.edit', function(element) {
    debugger
        var tr = $(element.target).closest('tr');
        **if(tr.hasClass('child'))
        {
            tr=$(tr).prev();
        }**
        var data = table.row(tr).data();
        console.log(data.id);
      });
    });

Answer №3

When using this code snippet, remember to utilize the attribute data-id

$(document).ready(function() {
  var table = $('#example').DataTable({
    "columns": [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'office'
      },
      {
        data: 'age'
      },
      {
        data: 'salary'
      },
      {
        data: null,
        render: function(data, type, row) {
          return '<a href="javascript:void(0)" data-id="' + data.id + '" class="btn btn-link btn-warning btn-icon btn-sm edit"><i class="fas fa-pencil-alt"></i></a>';
        }
      }
    ],
    responsive: true
  });

  var users = [{
      id: 1,
      name: "Penny",
      position: "waitress",
      office: "none",
      age: "25",
      salary: "1550$"
    },
    {
      id: 2,
      name: "Sheldon",
      position: "physical",
      office: "university",
      age: "39",
      salary: "8435$"
    },
    {
      id: 3,
      name: "Leonard",
      position: "physical",
      office: "university",
      age: "35",
      salary: "7842$"
    },
  ];

  $('#example').DataTable().clear().draw();
  $('#example').DataTable().rows.add(users);
  $('#example').DataTable().draw();

  $('#example').on('click', '.edit', function(element) {

    /*var tr = $(element.target).closest('tr');
    var data = table.row(tr).data();
    console.log(data.id);*/
    var id = $(this).data('id')
    console.log(id);

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script>
<link href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" rel="stylesheet"/>
<link href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" rel="stylesheet"/>

<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Salary</th>
      <th class="sorting_desc_disabled sorting_asc_disabled">Action</th>
    </tr>
  </thead>

  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Salary</th>
      <th class="sorting_desc_disabled sorting_asc_disabled">Action</th>
    </tr>
  </tfoot>

  <tbody>
  </tbody>
</table>

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

Emphasize certain VueJS elements for focus

Currently, I am working with a Vue file and I'm interested in highlighting the active element. Can you recommend the most efficient method to achieve this? <li @click = "selectedComponent = 'appBugs1'"><i class="ion-bug"></i& ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

What is the best way to set up a React handler that can handle multiple values effectively?

Struggling with a handler that is not behaving as expected. I need to update the 'quantity' value of multiple items, but currently they all get updated with the last value entered. How can I change multiple values and update items individually? H ...

What is the process for removing the body of a table?

My goal is to reset the table body, which has been filled with JavaScript loaded data previously. https://i.stack.imgur.com/7774K.png ` getTableData = function (clicked_id) { if (clicked_id != '') { $.ajax({ async : f ...

When using JavaScript to redirect with window.location, the referrer header is not properly set

Currently, I am attempting to utilize window.location in React to redirect to a third-party page. However, upon making the redirect, the third-party server is not receiving a referrer header from my redirection. Any assistance on resolving this issue wou ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

How can we trigger a function once an ajax request has finished, without directly interacting with the ajax

I am facing a challenge where I need to trigger a JS function after an ajax call is completed, specifically when filtering posts in WordPress. The issue lies in the fact that the ajax filter tool in use is part of a WordPress plugin that cannot be modified ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

Encountering a React clash while integrating Material UI

Upon trying to utilize the AppBar feature in Material UI version 0.16.6, I encountered the following error: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created within a c ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Are desktop values taking precedence over the mobile media query?

Currently, I am facing an issue with aligning icons (images) under each title on a page that lists various classes. The icon needs to be centered below the title on both desktop and mobile versions of the site. However, I have encountered a problem where u ...

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

Javascript - Conceal a Dynamic Div Depending on its Text

I have a unique table that generates dynamic Divs with ID's that count as they are created in the following format: <div id="dgpCheckDiv10_0"> <input Delete </div> <div id="dgpCheckDiv10_1"> text2 </div> Some of t ...

I'm unable to select a checkbox using Python Selenium

My attempt to create a checkbox using Python Selenium resulted in an error message. selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable I believe the issue lies with the element, but I am unsure of its exact locat ...