Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table.

Currently, my code successfully deletes the entire row (good) and transfers it to the other table (also good), but it includes the button as well, which is not intended. Moreover, the formatting gets skewed, and I cannot seem to identify the cause of this issue.

Code:

HTML

<body>
    <h1>Your Friends</h1>
    <div class="mx-auto" style="width: 700;">
        <table id="existingFriends" class="table table-striped table-dark table-hover">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Office</th>
                    <th scope="col">Friend Level</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Dwayne 'The Rock' Johnson</td>
                    <td>Dallas></td>
                    <td>Top Dog/BFF</td>
                </tr>
            </tbody>
        </table>
    </div>
    <h1>Suggested Friends</h1>
    <div class="table-container" style="width:500;" align="center;">
        <table id="addFriends" class="table table-striped table-dark table-hover">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Office</th>
                    <th scope="col">Friend Level</th>
                    <th scope="col">Add</th>
                </tr>
            </thead>
            <tbody>
                <tr id="ryan">
                    <td>Ryan Reynolds</td>
                    <td>Dallas</td>
                    <td>Acquaintance</td>
                    <td>
                        <a role="button" class="btn btn-success btn-sm" value="Shift Row" onclick="shiftFunc(); putBack();">
                            <i class="fas fa-check-square"></i>
                        </a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

JS

<script language="javascript">
        var row = document.getElementById("ryan");
        function shiftFunc() {
            row.parentNode.removeChild(row);
        }
        function putBack() {
            var tbl = document.getElementById("existingFriends");
            tbl.appendChild(row);
        }
    </script>

Picture Output: Before Click

Picture Output: After Click

Both solutions provided address the movement of rows between tables. However, I have decided not to address the formatting issue, as I am now required to convert everything to React, which does not support inline JavaScript functions like value or onclick.

Answer №1

If you want to make the table cell with the add button selectable with a query selector and removable, you can assign it a class.

To enhance the functionality of the adding button, consider passing 'this' as an argument to the function and setting 'row' as the 'parentNode' of the parent element of the button. This adjustment will allow the function to work for multiple rows.

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>

    <h1>Your Friends</h1>
    <div class="mx-auto" style="width: 700;">
        <table id="existingFriends" class="table table-striped table-dark table-hover">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Office</th>
                    <th scope="col">Friend Level</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Dwayne 'The Rock' Johnson</td>
                    <td>Dallas></td>
                    <td>Top Dog/BFF</td>
                </tr>
            </tbody>
        </table>
    </div>
    <h1>Suggested Friends</h1>
    <div class="table-container" style="width:500;" align="center;">
        <table id="addFriends" class="table table-striped table-dark table-hover">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Office</th>
                    <th scope="col">Friend Level</th>
                    <th scope="col">Add</th>
                </tr>
            </thead>
            <tbody>
                <tr id="ryan">
                    <td>Ryan Reynolds</td>
                    <td>Dallas</td>
                    <td>Acquaintance</td>
                    <td class="addColumn">
                        <a role="button" class="btn btn-success btn-sm" value="Shift Row" onclick="shiftFunc(this); putBack();">
                            <i class="fas fa-check-square"></i>
                        </a>
                    </td>
                </tr>
                 <tr id="daniel">
                    <td>Daniel </td>
                    <td>Dallas</td>
                    <td>Acquaintance</td>
                    <td class="addColumn">
                        <a role="button" class="btn btn-success btn-sm" value="Shift Row" onclick="shiftFunc(this); putBack();">
                            <i class="fas fa-check-square"></i>
                        </a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <script language="javascript">
        var row = document.getElementById("ryan");
        function shiftFunc(elem) {
            row = elem.parentNode.parentNode;
            row.parentNode.removeChild(row);
        }
        function putBack() {
            var tbl = document.getElementById("existingFriends");
            var add = row.querySelector('.addColumn');
            row.removeChild(add);
            tbl.appendChild(row);
        }
    </script>
</body>
</html>

Answer №2

To successfully integrate your javascript, follow these steps:

<script language="javascript">
        var element = document.getElementById("mark");
        function moveElement() {
            element.parentNode.removeChild(element);
        }
        function returnElement() {
            var table = document.getElementById("friendList");
            element.lastElementChild.remove();
            table.appendChild(element);
        }
</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

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

What steps can I take to resolve the TypeError in next js where I am unable to set properties of undefined for 'className'?

I've been working on a Next.js project and I've copied some code from CodePen that is used for designing product layouts on an e-commerce website. However, I'm encountering a problem with the following error message: TypeError: Cannot set pr ...

Is it possible to customize the appearance of a toast notification using Toastr beyond the default settings? If so, what options are available for creating

Working with Angular 9 and ngx-toastr has presented me with an interesting challenge. I am tasked with creating custom toast styles that differ significantly from the default ones provided by toastr. Each toast in the set will have unique border colors, f ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...

Switch videos within the video tag as you scroll

I am trying to implement a video tag within a div element on my website. Here is the current code: <div class="phone" align="center"> <div class="phone-inner"> <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo ...

The vacant array suddenly fills up with content once it is accessed

I encountered a strange scenario where the console.log indicated that the array was empty. However, upon inspection, I found 2 elements within it. This unexpected behavior prevented the component from rendering as it believed that conversations was empty. ...

Retrieve the current language from a non-page component on the server side with the help of Next.js and the next-i18next

I am working on a nextjs application that utilizes the next-i18next library for internationalization. I'm struggling to figure out how to access the current language on the server-side within a component that is not a page. On the server side, you ca ...

Add to and subsequently remove the possibility of deleting that element

I encountered an issue while moving elements from one div (x) to another div (y). The problem is that the elements in div x are deletable, but once they are copied to div y, they cannot be deleted. Here is the initial state: https://i.sstatic.net/4yQ6U.pn ...

PHP overall outcome

I have created a form that includes checkboxes, but I am facing difficulty in calculating the total result based on the selections. Ideally, if a user selects three checkboxes, the total should be $3, and if only one checkbox is selected, the total should ...

Upon attempting to utilize Socket.io with Next.JS custom server, the server repeatedly restarts due to the error message "address already in

Every time I attempt to execute the refreshStock() function within an API endpoint /api/seller/deactivate, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (net.js:1318: ...

Refreshing express-session sessions

My goal is to enhance the user experience by retrieving their profile from the mongodb database when they visit the page, and then updating their session with this information. Currently, I am utilizing the following packages for managing sessions: - ex ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Challenges arise when trying to load CSS on an EJS page in conjunction with using res.redirect()

When using Express with EJS, my base route is set as follows: router.get("/", productsData.getProducts); The "productsData" is sourced from my controllers page and the code snippet within that page is as follows: exports.getProducts = (req, res, next) => ...

Enable automated addition or alteration of phone numbers through Twilio's API

I'm looking to programmatically add and edit phone numbers using the API on this Twilio link. Can you guide me on how to achieve this? ...

Is it possible to generate multiple modal windows with similar designs but varying content?

I am facing a challenge with 140 link items that are supposed to trigger a modal window displaying a user profile for each link. The issue is that each user profile contains unique elements such as three images, a profile picture, text paragraph, and socia ...

Tips for dividing a div into percentages while maintaining a constant width for a div on the left side

I need help with creating a layout that involves 4 boxes. The first box (box1) should have a width of 50px on the left side, while the remaining 3 boxes should fill in the rest of the screen and be resizable. Can someone guide me on achieving this layout? ...

Contrasting $interval and setInterval functions in AngularJs

I am trying to grasp the distinction between $interval and setInterval. I have come up with this test: Dashboard.prototype.updateTotalAppointments = function(){ //console.log(); this.appointmentsCount = this.appointmentsCount +1; console.log(this.appointm ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

What is the best way to maintain the selected row during pagination in Yii?

Currently, I am facing an issue with pagination while viewing table rows. My requirement is to select different rows from various pages and then submit the form. The problem occurs when I select rows from one page, navigate to another page to make more se ...