user6197965
user6197965

Reputation:

Making table rows sortable

How exactly I can make table rows sortable when they are loaded on page via ajax? I have on the page markup where I load the table via ajax

<div id="mycart" style="text-align:center;"> </div>

This is the script with which I trying to sort tr's on the table

$(document).ready(function() {
   var fixHelperModified = function(e, tr) {
   var $originals = tr.children();
   var $helper = tr.clone();
   $helper.children().each(function(index) {
       $(this).width($originals.eq(index).width())
   });
   return $helper;
},
updateIndex = function(e, ui) {
    $('td.index', ui.item.parent()).each(function (i) {
        $(this).html(i + 1);
    });
};

$("#sort tbody").sortable({
   helper: fixHelperModified,
   stop: updateIndex
}).disableSelection();
});

When I put $("#mycart tbody").sortable({ it is working but is moving whole mycart div. So how can I select table which isn't "really" on the page... in source of the page I see only <div id="mycart" style="text-align:center;"> </div>.. I don't see actual table. Here is the js whit which I pull data

function show_cart()
{
  $.ajax({
  type:'post',
  url:'includes/store_items.php',
  data:{
    showcart:"cart"
  },
  success:function(response) {
    document.getElementById("mycart").innerHTML=response;

    $("#mycart").slideToggle();
  }
 });

Upvotes: 0

Views: 619

Answers (1)

hmd
hmd

Reputation: 970

I think you need to call the same JQuery Sortable function in your ajax request's success callback, right after putting the new HTML:

 success:function(response) {   

     document.getElementById("mycart").innerHTML=response;
     // or $("#mycart").html(response);

     $("#sort tbody").sortable({
        helper: fixHelperModified,
        stop: updateIndex
     }).disableSelection();

     $("#mycart").slideToggle();

}

Update: And you may need to move the following functions outside the $(document).ready({});:

var fixHelperModified = function(e, tr) {
   var $originals = tr.children();
   var $helper = tr.clone();
   $helper.children().each(function(index) {
       $(this).width($originals.eq(index).width())
   });
   return $helper;
},
updateIndex = function(e, ui) {
    $('td.index', ui.item.parent()).each(function (i) {
        $(this).html(i + 1);
    });
};

Upvotes: 3

Related Questions