Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ui sortable tablerows refresh number position inside

In a html table I have in every row a cell with its own position number. How can I refresh this position number correctly after sorting with jQueryUI?

This is my simple html:

<table border="0">
<thead>
      <tr>
        <th scope="col">Position number</th>
        <th scope="col">Name</th>
      </tr>
  </thead>
  <tbody>
      <tr>
        <td>1</td>
        <td>Text</td>
      </tr> 
      <tr>
        <td>2</td>
        <td>Text</td>
      </tr>
  </tbody>        
</table>

And this is my js:

    var fixHelper = function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; };

    $("table tbody").sortable({ 
        helper: fixHelper
    }).disableSelection();

Now I'd like to change order correctly position number values after complete sorting.

How can I make this?

Any help would be appreciated.

like image 925
bobighorus Avatar asked Jan 05 '12 10:01

bobighorus


2 Answers

Do the following after sorting ..

$("table tbody").sortable({ 
    update: function(event, ui) {  
        $('table tr').each(function() {
            $(this).children('td:first-child').html($(this).index())
        });
    },
    helper: fixHelper
}).disableSelection();

you can try (untested) : instead of $('table tr').each use $(this).parents('table').find('tr').each

Explanation.. It loops through each of the tr tags within table and then changes the content of first td-child with the index value of tr

like image 74
Gaurav Shah Avatar answered Nov 01 '22 00:11

Gaurav Shah


If anybody liked the above answer as I did, here's the Coffeescript

jQuery ->
  $("ul.sortableEdit").sortable
            stop: (event, ui) ->  
             $('ul.sortableEdit li').each( ->
               $(this).children('input.sortableItemPos').val($(this).index())
             )
like image 40
Brendan Murphy Avatar answered Nov 01 '22 02:11

Brendan Murphy