Shuffling specific table cells to exchange positions

I am attempting to create a script that will allow certain td elements (but not all) in different tr elements to switch places with the ones directly above or below them. My goal is to only target the last 3 td elements in each row, rather than the entire row. I have been struggling to find a solution that will specifically target these 3 td elements without affecting the rest of the row.

You can view the example I have created here: http://codepen.io/anon/pen/qwHbz

I am aware that a simple solution like the following can swap entire rows:

$("#Row1").after($("#Row2"));

However, I am interested in targeting only the specific td elements within each row. For example, if I were to click .saTableDown on the first row that contains it, I would like the Target, Level, and Instruction td elements to swap with the ones below it, and so on. Is it possible to achieve this using jQuery or JavaScript? I have been unable to find a solution so far. Thank you for your help!

Answer №1

Is this the solution you were looking for?

http://codepen.io/anon/pen/rEJxH

To achieve the desired functionality, the script finds the index of the clicked tr element and swaps it with the previous or next tr if it's not the first or last element. The code assumes you have access to the necessary HTML markup to assign classes to the number and target elements within the table rows.

Here's the jQuery code snippet:

$('.saTableUp').click(function(){
    var parentTr = $(this).parent().parent();
    var index = parentTr.index();

    if (index > 1) {
      var parentSwap = parentTr.prev();
      parentSwap.before(parentTr);
      parentTr.children('.num').before(parentSwap.children('.num'));
      parentSwap.children('.target').before(parentTr.children('.num:eq(1)'));
    }
});

$('.saTableDown').click(function(){
    var parentTr = $(this).parent().parent();
    var index = parentTr.index();

    if (index < 4) {
      var parentSwap = parentTr.next();
      parentSwap.after(parentTr);
      parentTr.children('.num').before(parentSwap.children('.num'));
      parentSwap.children('.target').before(parentTr.children('.num:eq(1)'));
    }
});

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

Managing State with Vuex: Storing Getter Results in the State

I'm encountering an issue with my Vuex.Store: My goal is to retrieve an object (getter.getRecipe) by using two state entries as search criteria (state.array & state.selected) through a getter. Then, I want to store the outcome in my state (state. ...

Send information from a dropdown selection to mysql database without needing to reload the page

Looking for a way to submit data from a dropdown menu to a PHP script without refreshing the page? Currently, when a user selects an option from the dropdown menu, the form action directs it to a PHP script that updates the database query. Below is the cod ...

Calculate the overall length of a specified time interval using Node Js

My task involves calculating overtime based on work start and end times. We are looking to calculate overtime hours that fall outside of the regular work schedule. For example, the regular work timings are from 10:00 AM to 07:00 PM Overtime needs to be ...

The header and footer are not extending across the entire width of the page

While testing on a responsive screen, I noticed that the header and footer both decrease in width instead of maintaining 100% width as intended. The issue only occurs when I reduce the width of the screen. body{ margin: 0; padding: 0; box-si ...

Error encountered when sending information to web service repeatedly

After populating an array with data, the information is logged into a database using a web service when the array reaches a specific record count. However, upon calling the web service, I encountered an error related to a parameter being passed: Error Ty ...

There seems to be a caching issue in ReactJS and Spring Data Rest that could be causing problems with

Encountering an unusual caching problem here. Just recently wiped out my database. While adding new users to the system, an old user mysteriously reappeared. This user has not been recreated and is not in the current database whatsoever. I'm at a lo ...

What are the semantics behind implementing Basic Authentication in AngularJS and Spring Boot?

Currently going through a tutorial that involves AngularJS and Spring Security. The AngularJS navigation controller triggers an authenticate function upon page load: var authenticate = function(credentials, callback) { var headers = credentials ? { ...

Are the nav, footer, header tags not functioning correctly?

Hi everyone, I'm a newcomer to StackOverFlow! I have a question about the necessity of tags like Nav, footer, header, etc. Do they serve any purpose other than indicating what each section is about? I've heard they might be good for SEO rankings ...

JavaScript problem encountered when using the forEach() function on $el

I am encountering an issue where I am unable to access the element value inside the forEach() function var filtered = rawData.map(function(x){ return { state : x.state, active : x.active, deaths : x.de ...

Every time I try to run npm start on my React app, I keep receiving the error message "? Something is already running on port 3000"

Whenever I try to start my React server, I keep receiving the message "? Something is already running on port 3000" in my terminal. Strangely, there is nothing actually running on port 3000. Here are the steps I have taken to try and solve this issue: Re ...

The RequiredFieldValidator and RegularExpressionValidator are not functioning properly

I have the following code snippet in one of my "C#" aspx pages. Despite having validation set up, the event attached to cmdPassword still fires even when the textbox is empty. Why are the validations not working? <tr> <td align="left" valign="t ...

The unusual behavior of a page refresh in jQuery when replacing content

My website features a flash player. This code references the flash player stored in player_codes.php: <script language="javascript" type="text/javascript" src="songs_related/flashmp3player/swfobject.js" ></script> <!-- Div that contains pl ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

Tips on how to patiently wait until the database connection is established and all queries are successfully executed for every database specified in an array

A file containing JSON data with database details needs to execute a series of queries for each database connection. The map function is currently waiting for the database connection. Below is the start function function start() { console.log('func ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

Track when a user modifies a <select> dropdown list generated using the Jquery method ".html()"

Is it possible to detect a change in the value of a select list when that select list has been added using either the .html(htmlString) or .append(content[,content]) jQuery function? HTML CODE: <ul class="htmlClass"> <!-- Populated via JS --& ...

Angular Material selectionChanged function is providing the previous step instead of the current step

I need to make a page with two columns: one for a vertical stepper and the other for step descriptions. I want the description to update based on the current step selected. However, I am running into an issue where the selectedIndex shows the previously ch ...

I'm currently working on storing my data in a Node.js REST API, but I keep encountering an issue with the error message "req.status is not a function"

router.post('/savedata',function(req, res){ console.log(req.body); var data={ firstname:req.body.firstname, lastname:req.body.firstname, password:req.body.password, email:req.body.email, created:req ...

What is the proper method for transforming an Excel column containing JSON format data into a JavaScript object?

I am facing an issue with converting data from an excel sheet to json format. While the other columns convert successfully, one specific column containing json data is not being converted properly and instead gets treated as a string. Using JSON.parse() on ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...