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

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

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 sorting to the table if there are several rows (in addition to the title bar), otherwise the drag and drop function is superfluous.

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

+5
source share
2 answers

jquery filter() . . sortable :

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();
}
+5

nydcan , startDrag :

 function startDrag(event, ui) {
    var startIndex = ui.item.index();
    ui.item.data('startIndex', startIndex);
}

stopDrag :

function stopDrag(event, ui) {
    var startIndex = ui.item.data('startIndex');
    var endIndex = ui.item.index();
    if (startIndex != endIndex) {
        $.ajax({
            type: 'POST',
            url: '<%= ResolveUrl("~/MyPage.aspx/UpdateOrder") %>',
            contentType: 'application/json; charset=utf-8',
            data: "{ 'startIndex':'" + startIndex + "', 'endIndex':'" + endIndex + "'}",
            dataType: 'json',
            success: updateSuccess,
            error: updateError
        });
    }
}

- (VB.NET) :

<System.Web.Services.WebMethod()>
Public Shared Sub UpdateRulePriority(ByVal startIndex As Integer, ByVal endIndex As Integer)

    'Do stuff

End Sub

, .

0

All Articles