Tips for adjusting the placement of an object within a table

Below is an example of a basic table:

table, th, td {
  border: 1px black solid;
  border-collapse: collapse;
}
<table>
  <tr>
    <th>number</th>
    <th>name</th>
    <th>id</th>
  </tr>
  <tr>
    <td>1</td>
    <td>red</td>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>blue</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>yellow</td>
    <td>3</td>
  </tr>
</table>

I am looking to implement a feature that allows drag and drop functionality in the table. When an item is moved from one position to another, I want its number to change to match the position it was moved to, while keeping the name and id unchanged. For instance, if "blue" is moved to the first spot, its number should become 1 while its id remains 2, and similarly for other items. The overall goal is to maintain consistency in the table while allowing for reordering through drag and drop.

Any suggestions on how I can achieve this?

Answer №1

Utilize the drag event to create a copy of the target element when dragging is initiated, which will be necessary for handling drag-over events.

Once the drag operation concludes, rearrange the first td in each table row (tr) excluding any rows within the thead section by targeting the tbody.

let shadow
function dragit(event) {
    shadow = event.target;
}
function dragover(e) {
    let children = Array.from(e.target.parentNode.parentNode.children);
    if (children.indexOf(e.target.parentNode) > children.indexOf(shadow))
        e.target.parentNode.after(shadow);
    else
        e.target.parentNode.before(shadow);
}
function reOrder() {
    document.querySelectorAll(".myTable > tbody > tr > td:first-child").forEach(function (elem, index) {
        elem.innerHTML = (index + 1);
    });
}
table, th, td {
    border: 1px black solid;
    border-collapse: collapse;
}
 <table class="myTable">
    <thead>
        <tr>
            <th>number</th>
            <th>name</th>
            <th>id</th>
        </tr>
    </thead>
    <tbody>
        <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
            <td>1</td>
            <td>red</td>
            <td>1</td>
        </tr>
        <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
            <td>2</td>
            <td>blue</td>
            <td>2</td>
        </tr>
        <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
            <td>3</td>
            <td>yellow</td>
            <td>3</td>
        </tr>
    </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

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

Verify if a <select> element exists inside the main div

Is there a way for me to check if a <select> element is present within the parent div and display certain content based on its existence? Appreciate any assistance! ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...

Pass data to three.js using an input form

I'm trying to figure out how to pass the value of an input form to a three.js workspace. Here's my code where I want to use a slider to change the radius of a sphere, without relying on the built-in controls of three.js since I'm new to HTML ...

Tips for incorporating a dynamic basePath into your NextJS project

For my new app, I am trying to include the groupID in the URL before the actual path, such as 'https://web-site.com/1/tasks'. The NextJs docs mention a basePath that is set at build time and cannot be modified. With numerous routes in my current ...

Uploading information by merging form data with a fetch API reply

In my project, I am looking to merge two sets of data into a specific format and then make a post request. After using the fetch API, I received the following response: { "id":"some-id" } The JSON format of my form data is as follows: { "origin_ ...

Personalized design created using v-for

I have an array being passed through v-for and I want to use the values within the "style" attribute. Essentially, I need to append the value from v-for to style:"left"+EachValue+"px", but I'm having trouble with the syntax. I'm unsure if this ap ...

I'm noticing that my style.css changes are only showing up after a hard refresh, but then they revert back to an older version when I refresh normally

Apologies for the lengthy title. Here's the issue: I have a WordPress website with a custom theme and its corresponding child theme. Previously, updating the style.css file of the child theme would show the changes immediately after a website refresh ...

Learn how to incorporate an image into your Codepen project using Dropbox and Javascript, along with a step-by-step guide on having the picture's name announced when shown on the screen

Hey there, I'm in need of some assistance. I have a Codepen page where I am working on displaying 4 random shapes (Square, Triangle, Circle, and Cross) one at a time, with the computer speaking the name of each shape when clicked. I want to pull these ...

Transforming conversion code snippet from jQuery to Dojo - utilizing AJAX techniques

I am in the process of converting my code from jQuery to Dojo. I just need an equivalent snippet that works. The jQuery code is functioning properly, but the Dojo code is not working as expected. JQUERY <script type="text/javascript"> $(docume ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

The JSON.parse function encountered an Uncaught SyntaxError due to an unexpected token 'o

I'm struggling with this JSON data: const info = [{ "ID":1,"Name":"Test", "subitem": [ {"idenID":1,"Code":"254630"}, {"idenID":2,"Code":"4566"}, {"idenID":3,"Code":"4566"} ] }]; console.log(JSON.parse(info)); //U ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

Experiencing difficulties with using the javascript alternative to jQuery.ajax()

Here is a JavaScript Object: const data = { name: "John", age: 30, } const jsonData = JSON.stringify(data); The AJAX Request below successfully passes the data: $(function(){ $.ajax({ url:'two.php', ty ...

What steps should I take to make sure the vuex store is included in my build process?

I am currently working on a Vue application using vue cli 3. I found a guide here that explains how to build the app with vue-cli-service build --target wc --name my-element [entry] In order to test the output, I have created an index.html file: <!D ...

Content in the <core-animation-pages> element is extending beyond the borders of the main DIV when the "slide-from-right" effect is applied (Polymer

Check out this quick video I made to demonstrate the issue: I have successfully incorporated core-animation-pages into my web application. I have three different divs that transition using the slide-from-right animation without any problems. However, in d ...

Is there a way for me to perfectly align the image and the h1 header on the webpage?

I'm facing some challenges when it comes to aligning an image and an h1 tag on the same line. I've already tried using display: inline and inline-block, but they only affect the container of the two elements. I also set the width to 100% on the s ...

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...