Change the position on the second click

I am trying to implement a manual sorting feature for a table of persons. The idea is to allow users to select a person by clicking on the row, then select another person by clicking on them, and have the two selected rows switch positions without using drag and drop functionality.

While I have managed to select one row successfully, I am facing difficulty in selecting the second row. My current train of thought involves potentially using jQuery's replaceWith method to switch the positions of the selected rows.

$(document).ready(function(){

 var selections = new Array(2);

 $("tr").click(function() {

    var selected = $(this).attr('id');

    //highlight selected row
    $(this).toggleClass("marked");

  })

});

I have set up a fiddle demonstrating my progress: http://jsfiddle.net/zLz929xy/3

Any suggestions or guidance on how to tackle this issue would be greatly appreciated.

Answer №1

Check out this fiddle I made for you.

I've made some changes to your fiddle structure.

The code essentially checks if there is an existing "marked" element in the row and swaps the elements of the first row with those of the second row if found. You can also include var oldRowId = $(row).attr('id') and

var newRowId = $(element).attr('id')
to switch the row IDs as well.

In my opinion, this is the simplest way to achieve this.

$(document).ready(function(){
    $("tr").click(function() {
        var row = $(this);
        
        var check = false;
        $.each($('#people tbody tr'), function(idx, element) {
            if($(element).hasClass('marked')) {
                // old values from row
                var oldId = $(row).find('.id').html();
                var oldName = $(row).find('.name').html();
                
                // new values 
                var rowId = $(element).find('.id').html();
                var rowName = $(element).find('.name').html();
                
                // Replace element
                $(element).find('.id').html(oldId);
                $(element).find('.name').html(oldName);
                
                $(row).find('.id').html(rowId);
                $(row).find('.name').html(rowName);
            
            // check
                check = true;
            }
        });

        if(!check) {
            $(this).toggleClass("marked");
        } else {
            $.each($('#people tbody tr'), function(idx, element) {
            if($(element).hasClass('marked')) {
                $(element).toggleClass('marked');
                }
            });
        }
    })
});
html {
 font-family: Verdana;
 font-size: 10pt;
}

td{
border: 1px solid;
}

.marked {
 background: #e5e5e5;
 font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="people">
  <tbody>
    <tr>
        <th class="id">ID</th>
        <th class="name">Name</th>
    </tr>

    <tr id="user_1">
        <td class="id">1</td>
        <td class="name">Bob</td>
    </tr>
    <tr id="user_2">
        <td class="id">2</td>
        <td class="name">Carl</td>
    </tr>
    <tr id="user_3">
        <td class="id">3</td>
        <td class="name">Jane</td>
    </tr>
    <tr id="user_4">
        <td class="id">4</td>
        <td class="name">Steven</td>
    </tr>
    <tr id="user_5">
        <td class="id">5</td>
        <td class="name">Sarah</td>
    </tr>
    <tr id="user_6">
        <td class="id">6</td>
        <td class="name">Marc</td>
    </tr>
  </tbody>
</table>

Answer №2

I have simplified the process by avoiding arrays, loops, and checking classes when removing the "marked" class. As we only need to deal with one row marked as "marked", there is no necessity for iteration or class checks.

Furthermore, since we always switch the entire rows, we can simply extract all of their html content instead of dividing it into distinct pieces for tracking and manipulation.

$(document).ready(function(){
    var somethingSelected = false;
    var firstRow;
    var firstRowHTML;
    var secondRow;

    $("tr").click(function() {
        if (somethingSelected) {
            secondRow = $(this);
            firstRow.html(secondRow.html());
            secondRow.html(firstRowHTML);
            somethingSelected = false;
            $("tr").removeClass("marked");
        } else {
            somethingSelected = true;
            firstRow = $(this);
            firstRowHTML = firstRow.html();
            $(this).addClass("marked");
        }
    }); 
});
html {
 font-family: Verdana;
 font-size: 10pt;
}

td{
border: 1px solid;
}

.marked {
 background: #e5e5e5;
 font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="people">

    <tr>
        <th id="id">ID</th>
        <th id="name">Name</th>
    </tr>

    <tr id="user_1">
        <td headers="id">1</td>
        <td headers="name">Bob</td>
    </tr>
    <tr id="user_2">
        <td headers="id">2</td>
        <td headers="name">Carl</td>
    </tr>
    <tr id="user_3">
        <td headers="id">3</td>
        <td headers="name">Jane</td>
    </tr>
    <tr id="user_4">
        <td headers="id">4</td>
        <td headers="name">Steven</td>
    </tr>
    <tr id="user_5">
        <td headers="id">5</td>
        <td headers="name">Sarah</td>
    </tr>
    <tr id="user_6">
        <td headers="id">6</td>
        <td headers="name">Marc</td>
    </tr>

</table>

Answer №3

Implementing the swap functionality as per the solution provided at this link:

var selections = new Array(2);

$("tr").click(function() {

  var selected = $(this).attr('id');

  //highlight selected row
  if ($('.marked').length) {
    $(this).swapWith($('.marked'));
    $('.marked').toggleClass("marked");
  }
  $(this).toggleClass("marked");
})


jQuery.fn.swapWith = function(to) {
  return this.each(function() {
    var copy_to = $(to).clone(true);
    var copy_from = $(this).clone(true);
    $(to).replaceWith(copy_from);
    $(this).replaceWith(copy_to);
  });
};
html {
 font-family: Verdana;
 font-size: 10pt;
}

td{
border: 1px solid;
}

.marked {
 background: #e5e5e5;
 font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="people">

  <tr>
    <th id="id">ID</th>
    <th id="name">Name</th>
  </tr>

  <tr id="user_1">
    <td headers="id">1</td>
    <td headers="name">Bob</td>
  </tr>
  <tr id="user_2">
    <td headers="id">2</td>
    <td headers="name">Carl</td>
  </tr>
  <tr id="user_3">
    <td headers="id">3</td>
    <td headers="name">Jane</td>
  </tr>
  <tr id="user_4">
    <td headers="id">4</td>
    <td headers="name">Steven</td>
  </tr>
  <tr id="user_5">
    <td headers="id">5</td>
    <td headers="name">Sarah</td>
  </tr>
  <tr id="user_6">
    <td headers="id">6</td>
    <td headers="name">Marc</td>
  </tr>

</table>

Answer №4

Personally, I believe adding a double click event to the second selection is essential as single clicks can be prone to accidental activation.

If not careful, mistakes could easily occur.

If you are open to this suggestion, you might want to consider implementing the dblclick event with the following code snippet;


$("tr").dblclick(function(e) {
    if ($('.marked').length == 1) {
        var marked     = $('.marked').html(),
            marked_id  = $('.marked').attr('id'),
            element    = $(this).html(),
            element_id = $(this).attr('id');
        $('tr[id="'+marked_id+'"]').html(element);
        $('tr[id="'+element_id+'"]').html(marked);
        $('tr').removeClass('marked');
    }
});

By checking if $('.marked').length is equal to 1, we ensure that the dblclick event is triggered only when one element is selected, making it easier to swap them out.

Simply store the html() of the TR along with their respective IDs for smooth swapping functionality.

View live preview here: http://jsfiddle.net/MrMarlow/zLz929xy/7/

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

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...

JavaScript doesn't seem to be functioning properly within PHP

I have implemented the supersized jQuery script to incorporate sliding backgrounds on my WordPress page. Now, I aim to create unique slides for different sites and require a PHP if request. This is my code: <?php if ( is_page(array('Restaurant&a ...

Tips for ensuring a scrollbar remains at the bottom position

I'm facing an issue with a scroll-bar inside a div element. Initially, the position of the scroll-bar is at the top. However, whenever I add text to the div element, the scroll-bar remains in its initial position and does not automatically move to the ...

The Feedback Form jQuery is not providing any data

I'm facing an issue with my html page that includes an ajax query to a php file. The purpose of this php file is to send a message and then return a response to the ajax query. However, no matter what I try, I am unable to receive any response from th ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...

What is the best way to display JSON within a partial?

Within my Rails app, I have implemented a JavaScript graph. Whenever I click on a circle in the graph, it displays the name of the corresponding user. Now, my goal is to retrieve additional information from the related database table based on this user&apo ...

The Kendo grid and Jquery functionalities seem to be malfunctioning on my View page

Looking to incorporate a progress bar using Jquery UI on my view page. The layout also includes a Kendo Grid component. I included the necessary files (jquery-ui.css, jquery-.js, jquery-ui.js) but encountered an error when adding jquery.js. The error mess ...

Creating animated image transitions (image swapping) using jQuery

In an attempt to animate images using jQuery and a timer, I am exploring the possibility of creating an effect similar to an animated GIF. The goal is to define the animation directly within the HTML file or in a script at the top of the page for repeated ...

tips for loading json data into jqgrid

Utilizing the struts2-jquery-jqgrid plugins, I have created a Grid with a filter-search feature. The Grid includes a drop-down list in the column assigned_user for filtering based on the selected option from the drop-down list. <s:url var="remoteurl" a ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

Tips for utilizing a variable within a variable containing HTML code

Is it possible to incorporate variables in a JavaScript function that includes HTML code? Let's consider the following example: function SetCFonts() { var Color = $('#CColor').val(); var Font = $('#CFont').val(); var S ...

Fundamentals of object property in jQuery and Javascript

Currently working on creating a new property named startPosition and setting the top property to equal the button's current top value in CSS. Below is the jQuery code snippet: var morphObject = { button: $('button.morphButton'), c ...

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...

Pictures are not appearing correctly when utilizing the img-fluid class

Issues occur when I apply the "img-fluid" bootstrap class to my images, as they fail to appear on the page and are set at 0x0 pixels in size upon inspection. This is the HTML code: <div class="col"> <div class="row no-gutters"> &l ...

Font and div placement varies on a mac within a WordPress environment

www.oihanevalbuenaredondo.be After styling my post titles in CSS using font-family: adobe arabic, I noticed that while they display correctly on my Windows machine, they appear in a basic font on Mac OS, Safari specifically. Why is it that Safari cannot r ...

Cloning Div repeatedly instead of the specified quantity

My JSON data contains four sections and I want to clone my html div based on the number of sections. For example, if there are 100 sections in my JSON, I would like the div to be cloned 100 times. Currently, my div is getting cloned with the JSON data app ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...

Fetch data using hashchange event and jQuery based on the file name that is not included in the hash parameter

Currently, I am utilizing jQuery along with the hashchange plugin by Ben Alman. The following code snippet showcases a standard approach to retrieve the hash name and load content accordingly: $(window).hashchange(function() { var hash = location.hash; va ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...