Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sortable prevent some items from sorting?

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");
    }

;

like image 876
Jim Evans Avatar asked Jan 24 '14 17:01

Jim Evans


2 Answers

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 image 79
hgolov Avatar answered Sep 30 '22 19:09

hgolov


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();
        }
    }
});
like image 23
Paolo Bergantino Avatar answered Sep 30 '22 19:09

Paolo Bergantino