Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally apply jQuery Sortable UI widget to table (ASP.NET GridView)?

I have the following code which applies the jQuery UI Sortable plugin to all tables (GridView) on an ASP.NET page, excluding the first (header) row in each:

function pageLoad() {
    $('table').sortable({
        items: 'tr:not(:first)',
        axis: 'y',
        scroll: true,
        start: startDrag, //store start position
        stop: stopDrag    //get end position, update database
    }).disableSelection();

However I only want to apply sortable to a table if there is more than one row (in addition to the header row) otherwise the drag/drop functionality is redundant.

How can I conditionally apply the above only to tables having more than one content row? Thanks.

like image 346
Marcus Guinane Avatar asked Jul 26 '11 08:07

Marcus Guinane


1 Answers

jquery filter() provides a solution. It allows you to filter a set of matched elements using a test function. Therefore the following code applies sortable only to tables that have more than one data row:

function pageLoad() {

    $('table').filter(function () {
                        return $('tr', this).length > 2;
                      })
              .sortable({
                 items: 'tr:not(:first)',
                 axis: 'y',
                 scroll: true,
                 start: startDrag, //store start position
                 stop: stopDrag    //get end position, update database
                 })
              .disableSelection();
}
like image 51
James McCormack Avatar answered Nov 11 '22 21:11

James McCormack