Mohamad
Mohamad

Reputation: 35349

Referencing the top row of a table

I would like the following script to move a table row to the top of a table. I can't figure out how to reference the id of the first row, however, since the ID is set dynamically, I tried row.insertAfter(row.first()); but it's making the row disappear instead of moving it. Any ideas how to reference the top row?

    $(".top").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".top")) {
            row.inserAfter(row.first());
        } else {
            return false;
        }
    });


<tbody id="sortable">
  <tr id="row1">
    <td><a href="" class="top">Top</a></td>
  </tr>
  <tr id="row2">
    <td><a href="" class="top">Top</a></td>
  </tr>
  <tr id="row3">
    <td><a href="" class="top">Top</a></td>
  </tr>
</tbody>

Upvotes: 0

Views: 204

Answers (4)

ArtBIT
ArtBIT

Reputation: 3999

Do you wanna do something like this?

$(".top").click(function(){
    var $this = $(this); // make a reference to the current element
    $.ajax({
       url: 'your/ajax/url.php',
       success: function(data) {
          // do what you want with data,
          // and then move the row on top
          // of the table, like so
          var row = $this.parents("tr");
          var first_row = row.parent().find('tr:first');
          if (row && first_row && row != first_row) {
             row.insertBefore(first_row);
          }
       }
    });
    return false; // stay on the page
});

Check http://api.jquery.com/jQuery.ajax/ for more info

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82483

This works...

$(".top").click(function() {
  var thisRow = $(this).parent().parent();
  var firstRow = thisRow.parent().find("tr:first").not(thisRow);
  thisRow.insertBefore(firstRow);
});

Upvotes: 3

Bick
Bick

Reputation: 267

$(".top").click(function(){
            var tr=this.parentNode.parentNode;
    tr.parentNode.insertBefore(tr.parentNode.firstChild,tr);
    tr.parentNode.removeChild(tr);   
}

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

 var row = $(this).find("tr").eq(0);

Upvotes: -2

Related Questions