0

I am trying to implement a function which will change the elements order in a table. The logic is very easy: Each TR (except the first and the last ones) has a button_up and a button_down. When the user clicks one of those buttons, the element will change his place with the one above or below.

To do this, I am using jQuery and each TR has a unique Id and the buttons have a common class.

When a button with the specific class is clicked, I am executing this JavaScript code:

$('.upArrow').click( function(something)     
        {           
            var id = $(this).attr("id");

            var n=id.split("_");

            var new_id = '#row_'+n[1];

            var parent =$(new_id);
            var prev = $(new_id).prev();

            swap(prev, parent); 

            init_authors_list_ordering();
        });


        $('.downArrow').live('click', function()
        {
             var id = $(this).attr("id");

                var n=id.split("_");

                var new_id = '#row_'+n[1];

                var parent =$(new_id);
                var next = $(new_id).next();

                swap(next, parent); 

                init_authors_list_ordering();
        });
}

function swap(a, b, direction)
{
    var html = a.wrapInner('<tr></tr>').html();
    a.replaceWith(b.wrapInner('<tr></tr>').html());
    b.replaceWith(html);
}

The problem is that: The first time, everything works fine (my funxtion is not finished, I have to set some other parameters on change but the logic is there). But then, The two elements who changed their place have lost the TR's id, so they can't be touched anymore.

I don't know why the id is lost. This is the replaceWith() method.

Any help is welcome. Thank you.

Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

2 Answers2

1

To swap the elements, simply do:

function swap(a, direction, b) {
    a[direction](b);
}

and call like:

var firstElem  = $('#divID'),
    secondElem = $('#divID');

swap(firstElem, 'before', secondElem); // or after, whatever you need ?

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Your constant <tr></tr> has no id attribute, so it ends up with no id attribute.

EDIT: Here is what I reference:

function swap(a, b, direction)
{
    var html = a.wrapInner('<tr></tr>').html();
    a.replaceWith(b.wrapInner('<tr></tr>').html());
    b.replaceWith(html);
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100