Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and dropping rows in these dynamically generated tables. Can someone help me understand how I can make this work seamlessly for dynamically created tables as well?

  $(document).ready(function () {
      // Drag and drop
      $("#table-1").tableDnD({
          onDragClass: "myDragClass",
          onDrop: function (table, row) {
              var rows = table.tBodies[0].rows;
              for (var i = 0; i < rows.length; i++) {
                  debugStr += rows[i].id + " ";
                  alert(rows[i].id);
              }
          },
          onDragStart: function (table, row) {}
      });
  });

Answer №1

One potential reason for your issue could be that you are initializing .tableDnD() after the DOM has already loaded. If you are dynamically adding elements after this point, the function won't apply to those new elements.

To solve this problem, you can detect changes in the DOM and then apply .tableDnD() like this:

$(document).bind('DOMNodeInserted', function(){

    $("#table-1").tableDnD({
        onDragClass: "myDragClass",
        onDrop: function (table, row) {
            var rows = table.tBodies[0].rows;
            for (var i = 0; i < rows.length; i++) {
                debugStr += rows[i].id + " ";
                alert(rows[i].id);
            }
        },
        onDragStart: function (table, row) {}
    });

});

Alternatively, you can use a more efficient approach by applying .tableDnD() within the document ready function and binding it to the 'DOMNodeInserted' event:

$(document).ready({

    applyDnD();
    $(document).bind('DOMNodeInserted', applyDnD);

    function applyDnD() {
        $("#table-1").tableDnD({
            onDragClass: "myDragClass",
            onDrop: function (table, row) {
                var rows = table.tBodies[0].rows;
                for (var i = 0; i < rows.length; i++) {
                    debugStr += rows[i].id + " ";
                    alert(rows[i].id);
                }
            },
            onDragStart: function (table, row) {}
        });
    };

});

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

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

Installation and execution of TypeScript jQuery / Bootstrap definition file on a local machine using npm typings: A step-by-step guide

Struggling to set up TypeScript jQuery and Bootstrap definition files in my new project using npm typings. Below are the steps I followed: 1- Open cmd, navigate to my project folder, and enter the following commands: npm install typings --global typings ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Error: It is not possible to access the 'map' property of an undefined value 0.1

I'm currently experimenting with React.js and I encountered an error that's giving me trouble. I can't seem to pinpoint the root cause of this issue. Shout out to everyone helping out with errors: TypeError: Cannot read property 'map ...

Nextjs API call ended without a response being sent

I am currently facing a challenge in my NextJS project as my endpoint API does not support multiple calls, and I am looking to implement a data refresh every 3 minutes from the original source. To achieve this, I have integrated an API in NextJS by creati ...

The styling of a CSS class in Internet Explorer may not be applied correctly if there are multiple elements sharing the same class name

For nearly a full week now, I've been plagued by a persistent issue! Here's the situation: I have 6 step tabs - step 1, step 2, and so on. Each tab has a CSS class called "locked" and "active." "Locked" - this style features top: 3em;, causing ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

The table element fails to display in IE11 due to a rendering issue, displaying the error message: "Render error - TypeError: Object does not support the property or method 'entries'"

As someone new to web app development, I am currently working on a project that involves using Vue cli and antd components, with the additional challenge of ensuring compatibility with IE11. However, I have encountered an issue where IE11 does not render ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

Is there a way for me to display a customized error message using antd components?

During the registration process using React and Antd, if the backend returns the error message "user already registered" after clicking on "Sign up", it should be displayed in the form. You can customize the display as shown below: An example of how the u ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

Error message: The Javascript Electron app is unable to find the node-fetch module when

Below is the code snippet from my gate.html file: <html> <head> <meta http-equiv='Content-Security-Policy' content='default-src 'self'; https://example.com.tr/validkeys.txt'> <meta http-equiv=&ap ...