Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple rows and sort them in the same table using jquery sortable

Tags:

jquery

<table>
    <tbody>
        <tr>
            <th>Header1</th>
            <th>Header2</th>
            <th>Header3</th>
        </tr>
        <tr>
            <td>Data1</td>
            <td>Data2</td>
            <td>Data3</td>
        </tr>
        <tr>
            <td>Data4</td>
            <td>Data5</td>
            <td>Data6</td>
        </tr>
        <tr>
            <td>Data7</td>
            <td>Data8</td>
            <td>Data9</td>
        </tr>
        <tr>
            <td>Data10</td>
            <td>Data11</td>
            <td>Data12</td>
        </tr>
        <tr>
            <td>Data13</td>
            <td>Data14</td>
            <td>Data15</td>
        </tr> 
    </tbody>
</table>

$(function() {
    $('table tbody').sortable({
        items: 'tr:not(tr:first-child)',
        cursor: 'move',
        connectWith: 'table',
        axis: 'y',
        dropOnEmpty: true
    });

    $('table tr').on('click', function () {
        $(this).toggleClass('selectedRow');
    });
});


table tbody{
    background-color: greenYellow;
}


table tbody th{
    background-color: green;
}

.selectedRow{
    background-color: #abcdef;
}

Fiddle Here

How can I sort the table by inserting the rows selected at the specific row index.

like image 421
Suraj Shrestha Avatar asked Feb 28 '14 06:02

Suraj Shrestha


1 Answers

Got the answer:

$('table tbody').on('click', 'tr', function(e){
    if(e.ctrlKey || e.metaKey){
        $(this).toggleClass('selected');
    }else{
        $(this).addClass('selected').siblings().removeClass('selected');
    }
}).sortable({
    items: 'tr:not(tr:first-child)',
    connectWith: 'table',
    cursor: 'move',
    delay: 150,
    revert: 0,
    helper: function(e, item){
        if(!item.hasClass('selected')){
           item.addClass('selected').siblings().removeClass('selected');
        }

        var elements = item.parent().children('.selected').clone();
        item.data('multidrag', elements).siblings('.selected').remove();

        var helper = $('<tr/>');
        return helper.append(elements);
    },
    stop: function(e, ui){
        var elements = ui.item.data('multidrag');
        ui.item.after(elements).remove();
    }
});


table tbody{
    background-color: greenYellow;
}


table tbody th{
    background-color: green;
}

.selected{
    background-color: Azure;
}

Updated Fiddle Here

like image 151
Suraj Shrestha Avatar answered Nov 03 '22 14:11

Suraj Shrestha