tags:

views:

37

answers:

1

I have a table where users can move items up or down by one. I'm trying to disable a Move Item Up By One and Move Item Down By One buttons when a table row reaches the top or the bottom (becomes first or last). I don't know how to determine when a <tr> Item has reached the top or the bottom of the table.

This is what I'm using at the moment, which handles swapping the table rows when an item has been moved up or down.

    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
    });

I want to add a nested if statement under the first if statement, and another if statement under the else condition of the original if statement. The new conditional statements will be used to determine if the row has reached the top of the table, or the bottom of the table. I can then use this to enable/disable the buttons:

$(row).find('.up').find('input').attr('disabled','true');

The classes of the form buttons are up and down

So <form class="up"> <input type="submit"> </form> etc...

I'm not sure if this approach is the best, but I want to try it.

+2  A: 

You can try using prevAll() and nextAll() on the tr. if those return no results, it means the said tr is either the first or the last child.

$(".up,.down").click(function(){
    var row = $(this).parents("tr:first");
    if ($(this).is(".up")) {
        row.insertBefore(row.prev());
        if(row.prevAll().length == 0){
           //you just moved a row to the top. this is where you disable the button
           row.find('.up').find('input').attr('disabled','true');
           //the row that was the top before had its up disabled, enable it
           row.prev().find('.up').find('input').removeAttr('disabled');
        } 
    } else {
        row.insertAfter(row.next());
        //do same kind of thing here with nextAll
    }
});
mkoryak
mkoryak, do you mind giving me a small example please? I'm not sure how these would work, or were they would go into the code...
Mel
What I mean is, how can see if there's a result or not in the if condition... if (row.preAll() is an object... ?) { disable/enable goes here } ... I'm not sure how to test for the existence of an object in jQuery...
Mel
alright. ill provide some code. one sec
mkoryak
this could be optimized a ton, like row.prev() is used 2 times and should be extracted into a var.
mkoryak
mkoryak, if you feel up for it, go for it. I'm staying out of it since I don't have the knowledge or experience to optimize it. I will probably just break it. I would be interested to see how, but as it stands, it works! Thank you.
Mel