I have an HTML table that I am using jQuery UI sortable on and it is working just fine to allow me to drag and drop the row order in the table. I need to prevent certain rows from being sorted. These rows have a class ='nosort' and can be selected. They are always at the bottom. I am trying to use the cancel option of sortable to accomplish this with no success.
The HTML:
    <table id='sort'>
    <thead>
        <tr>
            <td>Col 1</td>
            <td>Col 2</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class='index'>Original Row 1</td>
            <td>Some Stuff</td>
        </tr>
        <tr>
            <td class='index'>Original Row 2</td>
            <td>Some Stuff</td>
        </tr>
        <tr>
            <td class='index'>Original Row 3</td>
            <td>Some Stuff</td>
        </tr>
        <tr class='nosort'>
            <td class='index'>Original Row 4</td>
            <td>Some Stuff</td>
        </tr>
        <tr class='nosort'>
            <td class='index'>Original Row 5</td>
            <td>Some Stuff</td>
        </tr>
    </tbody>
</table>
The Code:
$("#sort tbody").sortable({
    helper: fixHelperModified,
    stop: updateIndex
}).disableSelection()
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) {        
        $("#dvQMsg").hide();
        $("#dvQErr").hide();
        $("#dvSaveOrder").show();
        $('td.index', ui.item.parent()).each(function (i) {
            $(this).html(i + 1);
        });
        $(".nosort").sortable("cancel");
    }
;
I know this is an old question, but since it came up in my Google search others many see this. .sortable() has an option to set which items are sortable - items. In this case:
$( "#sort" ).sortable({
  items: "tr:not(.nosort)"
});
jQuery sortable: https://jqueryui.com/sortable/#items
Like I said in my comment, I normally use the beforeStop method when I want to cancel a sorting event based on some criteria. For example, I have a bunch of lists in one application and I want to be able to sort between them but not amongst them, and this can sometimes change on the fly. So I have something that looks like this:
$('#some_list').sortable({
    ...,
    beforeStop: function(e, ui) {
        if($(ui.item).closest('ul')[0] === this) { // don't allow within this
            e.preventDefault();
        }
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With