2
<tr id="r1">
  <td>1</td>
  <td>Some Text1</td>
  <td>Some Text1</td>
</tr>
<tr id="r2">
  <td>1</td>
  <td>Some Text2</td>
  <td>Some Text2</td>
</tr>
<tr id="r3">
  <td>3</td>
  <td>Some Text3</td>
  <td>Some Text3</td>
</tr>
<tr id="r4">
  <td>4</td>
  <td>Some Text4</td>
  <td>Some Text4</td>
</tr>
<tr id="r5">
  <td>5</td>
  <td>Some Text5</td>
  <td>Some Text5</td>
</tr>

I have a table which is organized as shown. What i'm trying to do, switching the rows of these table with user input.

For example: when user enters r1 and r3 the id's of these tables and "some text" parts should be changed and table should look like this.

<tr id="r3">
  <td>1</td>
  <td>Some Text3</td>
  <td>Some Text3</td>
</tr>
<tr id="r2">
  <td>1</td>
  <td>Some Text2</td>
  <td>Some Text2</td>
</tr>
<tr id="r1">
  <td>3</td>
  <td>Some Text1</td>
  <td>Some Text1</td>
</tr>
<tr id="r4">
  <td>4</td>
  <td>Some Text4</td>
  <td>Some Text4</td>
</tr>
<tr id="r5">
  <td>5</td>
  <td>Some Text5</td>
  <td>Some Text5</td>
</tr>

I tried to take values of one row to a temp variable and make a simple swap just like in OOP. However Jquery didn't let me do it :). What can i do to fix this?

1
  • Where are the inputs the ids are coming from? Commented Dec 4, 2011 at 17:27

2 Answers 2

3

To swap two elements, the following logic can be used:

  1. Insert a temporary placeholder after the second element
  2. Move the second element after the first element
  3. Replace the placeholder with the first element.

The implementation goes as follows:

var $elem1 = $("#r3"),
    $elem2 = $("#r1"),
    $placeholder = $("<tr><td></td></tr>");
$elem2.after($placeholder);

$elem1.after($elem2);
$placeholder.replaceWith($elem1);

In the previous sample, I have hard-coded the IDs. Assume that the user enters the IDs in fields with IDs from and to. Then, the implementation can be adjusted in this way:

var $elem1 = $("#" + $("#from").val()),
    $elem2 = $("#" + $("#to").val()),
    // same as first example,from line 3
Sign up to request clarification or add additional context in comments.

Comments

1

You can use prepend to push the wanted rows to the head of the table.

table.prepend($(selector)); 

A simple implementation looks like this:

$(function(){
    var table = $('#table');
    $('#swapper').keyup(function(event) {
        var value = $(this).val();
        var selector = '#' + $.trim(value).replace(/\s+/, ',#');
        if(selector) {
           table.prepend($(selector));
        }
    });
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.